1. CMSUser对象定义public class CMSUser {
private Integer userid;
private String username;
private String password;

public CMSUser(){}
public CMSUser(String username, String password){
this.username = username;
this.password = password;
}

public Integer getUserid() {
return userid;
}
        ....//以下省略get,set方法.2. CMSUser.hbm.xml文件<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.ailincms.bean">
<class name="CMSUser">
<id name="userid" type="java.lang.Integer">
<generator class="native" />
</id>
<property name="username" length="20" not-null="true" unique="true"/>
<property name="password" length="20" not-null="true" />
</class>
</hibernate-mapping>3. CMSUserService接口    //省略代码
4. CMSUserServiceBean方法实现@Service(value="cMSUserServiceBean") @Transactional
public class CMSUserServiceBean implements CMSUserService {
@Resource SessionFactory factory; public void createCMSUser(CMSUser cmsuser) {
factory.getCurrentSession().persist(cmsuser);
} public void updateCMSUser(CMSUser cmsuser) {
factory.getCurrentSession().merge(cmsuser);
} public void deleteByUsername(String... usernames) {
for(String username : usernames){
factory.getCurrentSession().delete(factory.getCurrentSession().load(CMSUser.class, username));
}
} public void deleteByUserid(Integer userid) {
factory.getCurrentSession().delete(factory.getCurrentSession().get(CMSUser.class, userid));
}

@Transactional(propagation=Propagation.NOT_SUPPORTED)
public CMSUser findByUsername(String username) {//return (CMSUser)factory.getCurrentSession().delete(factory.getCurrentSession().get(CMSUser.class, userid));
return (CMSUser)factory.getCurrentSession().createQuery("from CMSUser as user where user.username='"+username+"'");
//两种方法都试了,都报错。
}

@Transactional(propagation=Propagation.NOT_SUPPORTED)
public CMSUser findByUserid(Integer userid) {
return (CMSUser)factory.getCurrentSession().get(CMSUser.class, userid);
}

@SuppressWarnings("unchecked")
@Transactional(propagation=Propagation.NOT_SUPPORTED)
public List<CMSUser> getAllCMSUser() {
return factory.getCurrentSession().createQuery("from CMSUser").list();
}

}5. Junit测试public class CMSUser_CRUD {

private static CMSUserService userService; @BeforeClass
public static void setUpBeforeClass() throws Exception {
ApplicationContext act = new ClassPathXmlApplicationContext("beans.xml");
userService  = (CMSUserService)act.getBean("cMSUserServiceBean");
} @Test
public void createCMSUser() {
userService.createCMSUser(new CMSUser("xql","linlin520"));    //执行成功,未报错。
}

@Test
public void findByUserid(){
CMSUser cmsUser = userService.findByUserid(1);        ////执行成功,未报错。
System.out.println(cmsUser.getPassword());
}

@Test
public void findByUsername(){
CMSUser cmsUser = (CMSUser) userService.findByUsername("xql"); 
System.out.println(cmsUser.getPassword());
}
        
       //执行失败,报错。
}
报错信息如下:
java.lang.ClassCastException: org.hibernate.impl.QueryImpl cannot be cast to com.ailincms.bean.CMSUser
at com.ailincms.service.impl.CMSUserServiceBean.findByUsername(CMSUserServiceBean.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy10.findByUsername(Unknown Source)
at com.ailincms.Junit.CMSUser_CRUD.findByUsername(CMSUser_CRUD.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

解决方案 »

  1.   

    附上beans.xml的配置,不过这个应该没问题,应为save()和findById()可以执行<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-2.5.xsd
               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    <context:component-scan base-package="com.ailincms"/>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="org.gjt.mm.mysql.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ailincms?useUnicode=true&amp;characterEncoding=UTF-8"/>
    <property name="user" value="root"/>
    <property name="password" value="linlin520"/>
    <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
    <property name="initialPoolSize" value="1"/>
    <!--连接池中保留的最小连接数。-->
    <property name="minPoolSize" value="1"/>
    <!--连接池中保留的最大连接数。Default: 15 -->
    <property name="maxPoolSize" value="300"/>
    <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
    <property name="maxIdleTime" value="60"/>
    <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
    <property name="acquireIncrement" value="5"/>
    <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
    <property name="idleConnectionTestPeriod" value="60"/>
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
     <property name="mappingResources">
        <list>
          <value>com/ailincms/bean/CMSUser.hbm.xml</value>
        </list>
    </property>
     <property name="hibernateProperties">
     <value>
          hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
          hibernate.hbm2ddl.auto=update
          hibernate.show_sql=false
          hibernate.format_sql=false
      </value>
     </property>
    </bean>
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!--使用基于注解方式配置事务 -->
    <tx:annotation-driven transaction-manager="txManager"/>
    </beans>
      

  2.   

    org.hibernate.impl.QueryImpl cannot be cast to com.ailincms.bean.CMSUser
    应该是这两个文件有问题。你好好检查看看
      

  3.   

    楼上的兄弟,首先非常感谢你的回答,但希望下次能在你能理解代码的情况下再回答,否则会误导他人。报错信息应该是类型转换出错,但是CMSUser的类型定义并未找出有错误。特求助。
      

  4.   


    既然是类型转换错误,(CMSUser) userService.findByUsername("xql");看看这个方法,findByUsername先不要强制转换为CMSUser,给个Object,看看这个Object到底是什么?debug看。
      

  5.   

    我用了Junit怎么debug? 还有个问题就是不转CMSUser类型,直接转Object编辑通不过
      

  6.   


            @Test
    public void findByUsername(){
    CMSUser cmsUser = userService.findByUsername("xql");
    System.out.println(cmsUser.getPassword());
    }
    这个我不转换,直接写也不会报错,证明类型是正确的。而且在CMSUserServiceBean当中也定义了这方式的实现是返回CMSUser对象。
      

  7.   

     org.hibernate.impl.QueryImpl cannot be cast to com.ailincms.bean.CMSUser
    QueryImpl 不能转换为CMSUser类型,factory.getCurrentSession().createQuery("from CMSUser as user where user.username='"+username+"'")(这里还有后续方法);楼主你查看下吧,我好像记得是.list()的方法,然后这个查询也不是很好,中文名称有可能是相同的,那样你就不能确定其唯一性。
      

  8.   

    .lang.ClassCastException: org.hibernate.impl.QueryImpl cannot be cast to com.ailincms.bean.CMSUser报错信息,查询结里后类型转换出错了,应该在:factory.getCurrentSession().createQuery("from CMSUser as user where user.username='"+username+"'").addEntity(CMSUser.class);
    这样查询结果转为想要的类型。希望能对你有帮助。
      

  9.   


    非常感谢ce2010的回答,是少了list()方法,然后返回的是List<CMSUser>.问题已解决,请参考代码。1、CMSUserServiceBean
    //findByUsername@Transactional(propagation=Propagation.NOT_SUPPORTED)
    public List<CMSUser> findByUsername(String username) {
    return factory.getCurrentSession().createQuery("from CMSUser as user where user.username='"+username+"'").list();
    }
    2、Junit@Test
    public void findByUsername(){
    List<CMSUser> list = userService.findByUsername("xql");
    for (CMSUser cmsUser : list){
    System.out.println(cmsUser.getPassword());
    }
    }