simoi chigo
simoi chigo

Reputation: 589

spring org.hibernate.mappingexception unknown entity user

i'm new to spring i'm creating a new project to learn spring and now i'm facing a problem that i can't find the source of the problem.

the problem is that spring can't detect the entity bean and return a hibernate exception :

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)

here are my source code :

root-context :

    <?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 : Note that i'm using packagesToScan

<?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>

servlet-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 : Note that i'm using 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: [org.springframework.test.context.web.ServletTestExecutionListener@167c1fc, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@1ee9faa, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@38203, org.springframework.test.context.support.DirtiesContextTestExecutionListener@c285f4, org.springframework.test.context.transaction.TransactionalTestExecutionListener@1f3ddb1, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@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 org.springframework.context.support.GenericApplicationContext@1952a2d: 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: org.springframework.context.support.GenericApplicationContext@1952a2d: 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: org.springframework.context.support.GenericApplicationContext@1952a2d: 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 [org.springframework.jdbc.datasource.DriverManagerDataSource@12c5e02] of Hibernate SessionFactory for HibernateTransactionManager
INFO : org.springframework.test.context.transaction.TransactionContext - Began transaction (1) for test context [DefaultTestContext@95ec0 testClass = TestUserDao, testInstance = ma.solution.proeducation.dao.TestUserDao@120a5e0, testMethod = addUser@TestUserDao, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@10a9030 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 [org.springframework.orm.hibernate4.HibernateTransactionManager@943e88]; 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 [DefaultTestContext@95ec0 testClass = TestUserDao, testInstance = ma.solution.proeducation.dao.TestUserDao@120a5e0, testMethod = addUser@TestUserDao, testException = org.hibernate.MappingException: Unknown entity: User, mergedContextConfiguration = [MergedContextConfiguration@10a9030 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 [DefaultTestContext@95ec0 testClass = TestUserDao, testInstance = ma.solution.proeducation.dao.TestUserDao@fc5d40, testMethod = updateUser@TestUserDao, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@10a9030 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 [org.springframework.orm.hibernate4.HibernateTransactionManager@943e88]; 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 [DefaultTestContext@95ec0 testClass = TestUserDao, testInstance = ma.solution.proeducation.dao.TestUserDao@fc5d40, testMethod = updateUser@TestUserDao, testException = org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [ma.solution.proeducation.model.User#1], mergedContextConfiguration = [MergedContextConfiguration@10a9030 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 [DefaultTestContext@95ec0 testClass = TestUserDao, testInstance = ma.solution.proeducation.dao.TestUserDao@1429fac, testMethod = removerUser@TestUserDao, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@10a9030 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 [org.springframework.orm.hibernate4.HibernateTransactionManager@943e88]; 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 [DefaultTestContext@95ec0 testClass = TestUserDao, testInstance = ma.solution.proeducation.dao.TestUserDao@1429fac, testMethod = removerUser@TestUserDao, testException = org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [ma.solution.proeducation.model.User#1], mergedContextConfiguration = [MergedContextConfiguration@10a9030 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 org.springframework.context.support.GenericApplicationContext@1952a2d: 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();
    }

}

I don't see anythings wrong with my configuration or code please if you notice somthing or need more information don't hesitate.

Upvotes: 0

Views: 1625

Answers (2)

simoi chigo
simoi chigo

Reputation: 589

The problem is not from the configuration, the configuration is well done, but the probleme is in super.countAll("User"); in GenericDAO<T> :

GenericDAOImpl.java :

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

the solution is to change it to this :

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

I hope it will help someone and thank you @v.ladynev for your help !!.

Upvotes: 1

Maxinator
Maxinator

Reputation: 91

You have to define the path to the package that contains your mapping classes in the application.properties of your Spring application, somehow like this:

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

In your DatabaseConfig, add the the packages to scan to your session factory:

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

Hope that helps!

Upvotes: 0

Related Questions