0

I've been struggling with this all day but haven't yet found a solution.

I have a simple entity mapping to a database table:

@Entity
@Table(name = "PERSON")
public class Person implements Serializable {

// Attributes.    
@Id
@Column(name = "ID", unique = true, nullable = false)    
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;

@Column(name = "NAME", nullable = false, length=50)      
private String name;

@Column(name = "ADDRESS", nullable = false, length=100)
private String address;

@Column(name = "TELEPHONE", nullable = false, length=10)
private String telephone;

@Column(name = "EMAIL", nullable = false, length=50)
private String email;

@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="PERSON_ID")   
private List<Book> books;

// Constructors.
public Person() {
    this.id = 0;
    this.name = ("");
    this.address = ("");
    this.telephone = ("");
    this.email = ("");
    this.books = null;
}

This entity is governed by a Spring controller with the following method:

@RequestMapping(value = "/register", method = RequestMethod.POST)
public String post(@ModelAttribute("person") Person person, 
                   BindingResult bindingResult, 
                   SessionStatus sessionStatus,
                   Model model /* , 
                   HttpSession session */) throws DAOException {                  
    logger.info(PersonController.class.getName() + ".post() method called.");

    personValidator.validate(person, bindingResult);
    if (bindingResult.hasErrors()) {
        return "register";
    }
    else {

        // Write Person to database.
        personService.insert(person);

        // Set view.
        sessionStatus.setComplete();             
        return "options";            
    }
} 

The service class is:

@Service("personService")
@Transactional
public class PersonService {

@Autowired 
PersonDAO personDAO;

public void insert(Person person) throws DAOException {
    personDAO.insert(person);
}

And the DAO is as follows:

@Repository("PersonDAO")
public class PersonDAOImpl implements PersonDAO {

@Autowired
private SessionFactory sessionFactory;
static final Logger logger = Logger.getLogger(PersonDAOImpl.class.getName()); 

@Override
public void insert(Person person) throws DAOException {
    logger.info(PersonDAOImpl.class.getName() + ".insert() method called.");

    Session session = sessionFactory.openSession();
    Transaction transaction = session.getTransaction();
    try {
        transaction.begin();
        session.save(person);
        transaction.commit();
    }
    catch(RuntimeException e) {
        transaction.rollback();
        throw new DAOException(e);
    }
    finally {
        session.close();
    }
}

And of course the part of my Spring servlet binding everything together:

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>        
    <property name="hibernateProperties">
        <props>
           <prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
           <prop key="hibernate.show_sql">true</prop>
           <prop key="hibernate.current_session_context_class ">thread</prop>

           <!-- What to do with the database schema. -->
           <prop key="hbm2ddl.auto">validate</prop>    
           <!-- validate:    validate the schema, makes no changes to the database.
                update:      update the schema.
                create:      creates the schema, destroying previous data.
                create-drop: drop the schema at the end of the session. -->                 
        </props>            
    </property>                    
</bean>

So why am I getting the message:

org.hibernate.MappingException: Unknown entity: library.model.Person

If I try things like:

<property name="packagesToScan" value="library.model" /> 

<property name="annotatedClasses">
        <list>
            <value>library.model.Person</value>
        </list>
    </property>   

At the moment I am getting:

Jun 15, 2014 10:50:58 PM org.apache.catalina.core.ApplicationContext log INFO: Initializing Spring root WebApplicationContext Jun 15, 2014 10:51:02 PM org.apache.catalina.core.StandardContext listenerStart SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: library.services.PersonService library.controller.PersonController.personService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: library.dao.PersonDAOImpl library.services.PersonService.personDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'PersonDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.hibernate.SessionFactory library.dao.PersonDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/library-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/persistence/NamedStoredProcedureQuery at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:744)

3
  • Need more of the stack trace. Usually when I see something like this its a subtle typo. Commented Jun 15, 2014 at 21:44
  • Is the name of the table actually Person or is it person ? Commented Jun 15, 2014 at 21:45
  • The table is called Person in the application: it is called PERSON in the database. @Entity @Table(name = "PERSON") public class Person implements Serializable { Commented Jun 15, 2014 at 21:47

1 Answer 1

3

Try replacing:

<property name="annotatedClasses">
    <list>
        <value>library.model.Person</value>
    </list>
</property>  

With:

<property name="packagesToScan">
   <list>
       <value>library.model</value>
    </list>
</property>

In your sessionFactory properties.

If you get an error saying the property "packagesToScan" could not be found then you should add the spring-orm library to your project. If you're using maven then you can add:

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>YOUR SPRING VERSION HERE</version>
</dependency>
Sign up to request clarification or add additional context in comments.

13 Comments

I've tried what you said but I know have an error: `Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate4.annotation.AnnotationSessionFactoryBean] for bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/library-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate4.annotation.AnnotationSessionFactoryBean'
Are the Spring ORM jars definitely on the class path when you run the application and you're still using org.springframework.orm.hibernate4.LocalSessionFactoryBean as the session factory?
It#s a NetBeans project so all of the .jar files are in their own lib folder as part of the project itself. So yes.
If it can't find the class, that's usually a classpath problem. Not sure what you're using to run it, but can you check where it deploys application libraries and ensure that they're in the expected location ? Alternatively if everything is packaged in a war, make sure that the spring libs are in the war.
I am grateful. Thanks Matt Wilson.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.