spring4整合hibernate5报错

咕噜咕噜步步 发布于 2017/10/23 17:12
阅读 194
收藏 0

报错:

org.hibernate.MappingException: Unknown entity: cn.itheima.domain.User

    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
    at cn.itheima.test.HibernateTest.fun2(HibernateTest.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)


Process finished with exit code 255
 

 

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://www.springframework.org/schema/beans"
      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-4.2.xsd
                     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
                     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
                     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

   <!-- 读取db.properties文件 -->
   <context:property-placeholder location="classpath:db.properties" />
   <!-- 配置c3p0连接池 -->
   <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
      <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
      <property name="driverClass" value="${jdbc.driverClass}" ></property>
      <property name="user" value="${jdbc.user}" ></property>
      <property name="password" value="${jdbc.password}" ></property>
   </bean>

   <!-- 核心事务管理器 -->
   <bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager" >
      <property name="sessionFactory" ref="sessionFactory" ></property>
   </bean>

   <!-- 配置通知 -->
   <!-- <tx:advice id="txAdvice" transaction-manager="transactionManager" >
      <tx:attributes>
         <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
         <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
         <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
         <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
         <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
         <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
         <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
         <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
      </tx:attributes>
   </tx:advice> -->
   <!-- 配置将通知织入目标对象
   配置切点
   配置切面 -->
   <!-- <aop:config>
      <aop:pointcut expression="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))" id="txPc"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
   </aop:config> -->
   <!-- ========================================================================================= -->
   <!-- 开启注解事务 -->
   <tx:annotation-driven transaction-manager="transactionManager" />

   <!-- 将SessionFactory配置到spring容器中 -->
   <!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 -->
   <!-- <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
      <property name="configLocation" value="classpath:hibernate.cfg.xml" ></property>
   </bean> -->
   <!-- 加载配置方案2:在spring配置中放置hibernate配置信息 -->
   <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
      <!-- 将连接池注入到sessionFactory, hibernate会通过连接池获得连接 -->
      <property name="dataSource" ref="dataSource" ></property>
      <!-- 配置hibernate基本信息 -->
      <property name="hibernateProperties">
         <props>
            <!--  必选配置 -->
            <!--   <prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop>
                    <prop key="hibernate.connection.url" >jdbc:mysql:///crm_32</prop>
                    <prop key="hibernate.connection.username" >root</prop>
                    <prop key="hibernate.connection.password" >1234</prop> -->
            <prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop>

            <!--  可选配置 -->
            <prop key="hibernate.show_sql" >true</prop>
            <prop key="hibernate.format_sql" >true</prop>
            <prop key="hibernate.hbm2ddl.auto" >update</prop>
         </props>
      </property>
      <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
      <property name="mappingDirectoryLocations" value="classpath:cn/itheima/domain" ></property>
   </bean>

   <!-- action -->
   <!-- 注意:Action对象作用范围一定是多例的.这样才符合struts2架构 -->
   <bean name="userAction" class="cn.itheima.web.action.UserAction" scope="prototype" >
      <property name="userService" ref="userService" ></property>
   </bean>
   <!-- service -->
   <bean name="userService" class="cn.itheima.service.impl.UserServiceImpl" >
      <property name="ud" ref="userDao" ></property>
   </bean>
   <!-- dao -->
   <bean name="userDao" class="cn.itheima.dao.impl.UserDaoImpl" >
      <!-- 注入sessionFactory -->
      <property name="sessionFactory" ref="sessionFactory" ></property>
   </bean>
</beans>

HibernateTest.java

package cn.itheima.test;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.itheima.dao.UserDao;
import cn.itheima.domain.User;
import cn.itheima.service.UserService;

//测试hibernate框架
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class HibernateTest {
   @Resource(name="sessionFactory")
   private SessionFactory sf ;

   @Test
   //单独测试hibernate
   public void fun1(){
      Configuration conf = new Configuration().configure();

      SessionFactory sf = conf.buildSessionFactory();

      Session session = sf.openSession();

      Transaction tx = session.beginTransaction();
      //-------------------------------------------------
      User u = new User();

      u.setUser_code("rose");
      u.setUser_name("肉丝");
      u.setUser_password("1234");

      session.save(u);

      //-------------------------------------------------
      tx.commit();

      session.close();

      sf.close();

   }

   @Test
   //测试spring管理sessionFactory
   public void fun2(){

      Session session = sf.openSession();

      Transaction tx = session.beginTransaction();
      //-------------------------------------------------
      User u = new User();

      u.setUser_code("jack");
      u.setUser_name("杰克");
      u.setUser_password("1234");

      session.save(u);

      //-------------------------------------------------
      tx.commit();

      session.close();

   }

   @Resource(name="userDao")
   private UserDao ud;
   @Test
   //测试Dao Hibernate模板
   public void fun3(){

      User u = ud.getByUserCode("tom");

      System.out.println(u);
   }
   @Resource(name="userService")
   private UserService us;
   @Test
   //测试aop事务
   public void fun4(){
      User u = new User();

      u.setUser_code("hqy");
      u.setUser_name("郝强勇");
      u.setUser_password("1234");


      us.saveUser(u);
   }

}

User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itheima.domain" >
   <class name="User" table="sys_user" >
      <id name="user_id"  >
         <generator class="native"></generator>
      </id>
      <property name="user_code"  ></property>
      <property name="user_name"  ></property>
      <property name="user_password"  ></property>
      <property name="user_state"  ></property>

   </class>
</hibernate-mapping>

db.properties

jdbc.jdbcUrl=jdbc:mysql:///TestDB
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=0524
加载中
0
稻谷
稻谷

跟spring和hibernate都没关系。仔细阅读错误。这都需要伸手了么.

咕噜咕噜步步
咕噜咕噜步步
可是我的User是存在的也配置进去了,错在哪里了呢?
0
阿信sxq
阿信sxq

用惯了注解+spring jpa,一下看到这个还真看不懂了

0
独孤晓林

不用注解吗?

0
Kit_lee
Kit_lee

都Spring4的年代了还要用hbm.xml,看哭我了。话说我还真没看到啥错误,猜测应该还是配置问题吧。要不试试将model类换成注解方式?

0
yysf
yysf
没有扫描到你的实体类,应该是mappingDirectoryLocations配置问题,hibernate用的xml还是注解?
咕噜咕噜步步
咕噜咕噜步步
xml,但是我用上面的fun1测试是没有问题的,mappingDirectoryLocstions配置就在上面有什么问题呢?
返回顶部
顶部