2016-09-25 3 views
0

Я новичок в Spring Я создаю новый проект, чтобы узнать весну, и теперь я столкнулся с проблемой, что я не могу найти источник проблемы.spring org.hibernate.mappingexception неизвестный пользователь user

проблема заключается в том, что пружина не может обнаружить объектный компонент и возвращать гибернации исключение:

org.hibernate.MappingException: Unknown entity: User 
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096) 
at org.hibernate.internal.SessionImpl.getOuterJoinLoadable(SessionImpl.java:1758) 
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1663) 
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380) 
at org.hibernate.internal.CriteriaImpl.uniqueResult(CriteriaImpl.java:402) 
at ma.solution.proeducation.genericDAOImpl.GenericDaoImpl.countAll(GenericDaoImpl.java:53) 
at ma.solution.proeducation.daoImpl.UserDaoImpl.coutUsers(UserDaoImpl.java:39) 
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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) 
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) 
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) 
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280) 
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) 
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) 
at com.sun.proxy.$Proxy32.coutUsers(Unknown Source) 
at ma.solution.proeducation.dao.TestUserDao.addUser(TestUserDao.java:35) 
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:252) 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) 
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:191) 
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) 
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) 

вот мой исходный код:

корневой контекст:

<?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" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd"> 

    <!-- Root Context: defines shared resources visible to all other web components --> 

     <import resource="datasource.xml"/> 
     <import resource="servlet-context.xml"/> 
     <context:annotation-config/> 
     <context:component-scan base-package="ma.solution.proeducation"/> 
</beans> 

datasource.xml: Обратите внимание, что я пользуюсь пакетамиToScan

<?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:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context.xsd 
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx.xsd"> 

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="packagesToScan" value="ma.solution.proeducation.model" /> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
       <prop key="hibernate.show_sql">true</prop> 
       <prop key="hibernate.connection.pool_size">10</prop> 
       <prop key="configurationClass">org.hibernate.cfg.AnnotationConfiguration</prop> 
      </props> 
     </property> 
    </bean> 

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
     <property name="url" value="jdbc:mysql://localhost:3306/proeducation" /> 
     <property name="username" value="root" /> 
     <property name="password" value="1234" /> 
    </bean> 

    <tx:annotation-driven transaction-manager="transactionManager"/> 

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory" ref="sessionFactory" /> 
    </bean> 

</beans> 

сервлет-context.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 
     http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context.xsd"> 
    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> 

    <!-- Enables the Spring MVC @Controller programming model --> 
    <annotation-driven /> 
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> 
    <resources mapping="/resources/**" location="/resources/" /> 
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> 
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <beans:property name="prefix" value="/WEB-INF/views/" /> 
     <beans:property name="suffix" value=".jsp" /> 
    </beans:bean> 

    <context:component-scan base-package="ma.solution.proeducation.controller" /> 



</beans:beans> 

User.java: Обратите внимание, что я использую javax.persistence

package ma.solution.proeducation.model; 

import java.io.Serializable; 
import javax.persistence.*; 


/** 
* The persistent class for the users database table. 
* 
*/ 
@Entity 
@Table(name="users") 
@NamedQuery(name="User.findAll", query="SELECT u FROM User u") 
public class User implements Serializable { 
    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    @Column(name="id_users") 
    private int idUsers; 

    @Column(name="email_users") 
    private String emailUsers; 

    @Column(name="password_users") 
    private String passwordUsers; 

    public User() { 
    } 

    public int getIdUsers() { 
     return this.idUsers; 
    } 

    public void setIdUsers(int idUsers) { 
     this.idUsers = idUsers; 
    } 

    public String getEmailUsers() { 
     return this.emailUsers; 
    } 

    public void setEmailUsers(String emailUsers) { 
     this.emailUsers = emailUsers; 
    } 

    public String getPasswordUsers() { 
     return this.passwordUsers; 
    } 

    public void setPasswordUsers(String passwordUsers) { 
     this.passwordUsers = passwordUsers; 
    } 

} 

TestUserDao.java

package ma.solution.proeducation.dao; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.test.annotation.Rollback; 
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
import org.springframework.transaction.annotation.Transactional; 

import org.junit.Assert; 
import ma.solution.proeducation.model.User; 


@ContextConfiguration(locations = "classpath:root-context.xml") 
@RunWith(SpringJUnit4ClassRunner.class) 
public class TestUserDao { 

    @Autowired 
    UserDAO userDAO; 

    @Test 
    @Transactional 
    @Rollback(true) 
    public void addUser(){ 
     User user = new User(); 
     user.setEmailUsers("[email protected]"); 
     user.setPasswordUsers("Hello Moto"); 
     userDAO.saveUser(user); 
     user = new User(); 
     user.setEmailUsers("[email protected]"); 
     user.setPasswordUsers("Simoichigo"); 
     userDAO.saveUser(user); 

     Assert.assertEquals(new Long(2), userDAO.coutUsers()); 
     User user1 = userDAO.findById(2); 
     Assert.assertEquals("[email protected]", user1.getEmailUsers()); 
     Assert.assertEquals("Simoichigo", user1.getPasswordUsers()); 
    } 

    @Test 
    @Transactional 
    @Rollback(true) 
    public void updateUser(){ 
     User user = userDAO.findById(1); 
     user.setEmailUsers("[email protected]"); 
     user.setPasswordUsers("Bankai"); 
     userDAO.updateUser(user); 
     User user1 = userDAO.findById(1); 
     Assert.assertEquals("[email protected]", user1.getEmailUsers()); 
     Assert.assertEquals("Bankai", user1.getPasswordUsers()); 
    } 

    @Test 
    @Transactional 
    @Rollback(true) 
    public void removerUser(){ 
     User user = userDAO.findById(1); 
     userDAO.removeUser(user);  
     Assert.assertEquals(new Long(1), userDAO.coutUsers()); 
    } 

} 

- EDITED ---

UserDao.java:

package ma.solution.proeducation.dao; 
import java.util.List; 
import ma.solution.proeducation.model.User; 
public interface UserDAO { 
    public void saveUser(User user); 
    public void updateUser(User user); 
    public void removeUser(User user); 
    public List<User> findAll(); 
    public User findById(int id); 
    public Long coutUsers(); 
    public User findByEmail(String email); 
} 

UserDaoImpl.java:

package ma.solution.proeducation.daoImpl; 

import java.util.List; 

import org.hibernate.Criteria; 
import org.hibernate.criterion.Restrictions; 
import org.springframework.stereotype.Repository; 
import org.springframework.transaction.annotation.Transactional; 

import ma.solution.proeducation.dao.UserDAO; 
import ma.solution.proeducation.genericDAOImpl.GenericDaoImpl; 
import ma.solution.proeducation.model.User; 

@Repository 
@Transactional 
public class UserDaoImpl extends GenericDaoImpl<User> implements UserDAO { 

    public void saveUser(User user){ 
     super.save(user); 
    } 

    public void updateUser(User user){ 
     super.update(user); 
    } 

    public void removeUser(User user){ 
     super.remove(user); 
    } 

    public List<User> findAll(){ 
     return super.findAll("User"); 
    } 

    public User findById(int id){ 
     return super.findById(User.class, id); 
    } 

    public Long coutUsers(){ 
     return super.countAll("User"); 
    } 

    @Override 
    public User findByEmail(String email) { 
     Criteria criteria = super.getSessionFactory().getCurrentSession().createCriteria("User"); 
     criteria.add(Restrictions.eq("emailUsers", email)); 
     return (User) criteria.uniqueResult(); 
    } 

} 

- LOG CONSOLE -

INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] 
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [or[email protected]167c1fc, org.springframework.test[email protected]1ee9faa, org.springframewor[email protected]38203, org.springfra[email protected]c285f4, org.springframew[email protected]1f3ddb1, org.sp[email protected]bd1b6a] 
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [root-context.xml] 
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [servlet-context.xml] 
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [datasource.xml] 
INFO : org.springframework.context.support.GenericApplicationContext - Refreshing [email protected]52a2d: startup date [Mon Sep 26 21:43:30 WEST 2016]; root of context hierarchy 
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring 
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[GET]}" onto public java.lang.String ma.solution.proeducation.controller.HomeController.home(java.util.Locale,org.springframework.ui.Model) 
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: [email protected]52a2d: startup date [Mon Sep 26 21:43:30 WEST 2016]; root of context hierarchy 
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: [email protected]52a2d: startup date [Mon Sep 26 21:43:30 WEST 2016]; root of context hierarchy 
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0' 
INFO : org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver 
INFO : org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {4.0.5.Final} 
INFO : org.hibernate.Version - HHH000412: Hibernate Core {4.3.6.Final} 
INFO : org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found 
INFO : org.hibernate.cfg.Environment - HHH000021: Bytecode provider name : javassist 
INFO : org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect 
INFO : org.hibernate.engine.transaction.internal.TransactionFactoryInitiator - HHH000399: Using default transaction strategy (direct JDBC transactions) 
INFO : org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory - HHH000397: Using ASTQueryTranslatorFactory 
INFO : org.springframework.orm.hibernate4.HibernateTransactionManager - Using DataSource [[email protected]e02] of Hibernate SessionFactory for HibernateTransactionManager 
INFO : org.springframework.test.context.transaction.TransactionContext - Began transaction (1) for test context [[email protected] testClass = TestUserDao, testInstance = [email protected], testMethod = [email protected], testException = [null], mergedContextConfiguration = [[email protected] testClass = TestUserDao, locations = '{classpath:root-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [[email protected]43e88]; rollback [true] 
Hibernate: insert into users (email_users, password_users) values (?, ?) 
Hibernate: insert into users (email_users, password_users) values (?, ?) 
INFO : org.springframework.test.context.transaction.TransactionContext - Rolled back transaction for test context [[email protected] testClass = TestUserDao, testInstance = [email protected], testMethod = [email protected], testException = org.hibernate.MappingException: Unknown entity: User, mergedContextConfiguration = [[email protected] testClass = TestUserDao, locations = '{classpath:root-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]. 
INFO : org.springframework.test.context.transaction.TransactionContext - Began transaction (1) for test context [[email protected] testClass = TestUserDao, testInstance = [email protected], testMethod = [email protected], testException = [null], mergedContextConfiguration = [[email protected] testClass = TestUserDao, locations = '{classpath:root-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [[email protected]43e88]; rollback [true] 
Hibernate: select user0_.id_users as id_users1_0_0_, user0_.email_users as email_us2_0_0_, user0_.password_users as password3_0_0_ from users user0_ where user0_.id_users=? 
INFO : org.springframework.test.context.transaction.TransactionContext - Rolled back transaction for test context [[email protected] testClass = TestUserDao, testInstance = [email protected], testMethod = [email protected], testException = org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [ma.solution.proeducation.model.User#1], mergedContextConfiguration = [[email protected] testClass = TestUserDao, locations = '{classpath:root-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]. 
INFO : org.springframework.test.context.transaction.TransactionContext - Began transaction (1) for test context [[email protected] testClass = TestUserDao, testInstance = [email protected], testMethod = [email protected], testException = [null], mergedContextConfiguration = [[email protected] testClass = TestUserDao, locations = '{classpath:root-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [[email protected]43e88]; rollback [true] 
Hibernate: select user0_.id_users as id_users1_0_0_, user0_.email_users as email_us2_0_0_, user0_.password_users as password3_0_0_ from users user0_ where user0_.id_users=? 
INFO : org.springframework.test.context.transaction.TransactionContext - Rolled back transaction for test context [[email protected] testClass = TestUserDao, testInstance = [email protected], testMethod = [email protected], testException = org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [ma.solution.proeducation.model.User#1], mergedContextConfiguration = [[email protected] testClass = TestUserDao, locations = '{classpath:root-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]. 
INFO : org.springframework.context.support.GenericApplicationContext - Closing [email protected]52a2d: startup date [Mon Sep 26 21:43:30 WEST 2016]; root of context hierarchy 

- EDITED - GenericDaoImpl.java:

package ma.solution.proeducation.genericDAOImpl; 

import java.util.List; 

import org.hibernate.SessionFactory; 
import org.hibernate.criterion.Projections; 
import org.springframework.beans.factory.annotation.Autowired; 

import ma.solution.proeducation.genericDAO.GenericDAO; 

public class GenericDaoImpl<T> implements GenericDAO<T> { 

    @Autowired 
    private SessionFactory sessionFactory; 

    public SessionFactory getSessionFactory() { 
     return sessionFactory; 
    } 

    public void setSessionFactory(SessionFactory sessionFactory) { 
     this.sessionFactory = sessionFactory; 
    } 

    @Override 
    public void save(T entity) { 
     getSessionFactory().getCurrentSession().save(entity); 
    } 

    @Override 
    public void update(T entity) { 
     getSessionFactory().getCurrentSession().update(entity); 
    } 

    @Override 
    public void remove(T entity) { 
     getSessionFactory().getCurrentSession().delete(entity); 
    } 

    @SuppressWarnings("unchecked") 
    @Override 
    public List<T> findAll(String entityName) { 
     return getSessionFactory().getCurrentSession().createQuery("from "+entityName).list(); 
    } 

    @SuppressWarnings("unchecked") 
    @Override 
    public T findById(Class<T> classT,int id) { 
     return (T)getSessionFactory().getCurrentSession().load(classT, id); 
    } 

    @Override 
    public Long countAll(String entityName) { 
     return (Long) getSessionFactory().getCurrentSession().createCriteria(entityName).setProjection(Projections.rowCount()).uniqueResult(); 
    } 

} 

Я не вижу Anythings неправильно с моей конфигурации или код, пожалуйста, если вы заметили Somthing или необходима дополнительная информация, не стесняйтесь ,

+1

Пожалуйста, добавьте журнал с конфигурацией Hibernate (Hibernate log all entites) и с SQL для этого 'userDAO.saveUser (user);' –

+0

Пожалуйста, проверьте сообщение, я добавил то, что вы просили !!! –

+0

Похож, Hibernate может распознать 'User' как сущность. Возможно, проблема с 'super.countAll (« Пользователь »);' сама. –

ответ

1

Проблема не из конфигурации, конфигурация хорошо сделано, но Probleme в super.countAll("User"); в GenericDAO<T>:

GenericDAOImpl.java:

@Override 
    public Long countAll(String entityName) { 
     return (Long) getSessionFactory().getCurrentSession().createCriteria(entityName).setProjection(Projections.rowCount()).uniqueResult(); 
    } 

решение изменить его к этому:

@Override 
     public Long countAll(Class<T> classT) { 
      return (Long) getSessionFactory().getCurrentSession().createCriteria(classT).setProjection(Projections.rowCount()).uniqueResult(); 
     } 

Я надеюсь, что это поможет кому-то и поблагодарит вас u @ v.ladynev за вашу помощь !!.

+0

Добро пожаловать. Или вы можете использовать 'ma.solution.proeducation.model.User'. Просто Java Doc для метода 'createCriteria()' не ясен. –

0

Вы должны определить путь к пакету, который содержит классы отображения в application.properties вашего Spring приложения, как-то так:

entitymanager.packagesToScan: path.to.your.package.containingBeans 

В вашем DatabaseConfig добавьте пакеты для сканирования в ваш заводской счет:

sessionFactoryBean.setPackagesToScan(env.getProperty("entitymanager.packagesToScan")); 

Надеюсь, что это поможет!

+0

Я использую версию xml, а не версию объекта, как я могу добавить это в datasource.xml, указанный выше ?? –

Смежные вопросы