Im trying to configure a simple JPA project and im very stuck.
I have a working dataSource ( Oracle db ) with a table "SIMPLE" that contains an ID(NUMBER) and a WORD (VARCHAR2).
I keep getting an exception that sais there is something wrong with my named queries: SimpleObject.findById, SimpleObject.findAll, but they seem simple and i dont think I made mistakes there.
Here is the class that contains the queries. And I added all other classes and the full exception.
SimpleObject class that maps data from the table
package lt.tomas.proSpring3;
import javax.persistence.*;
#Entity
#Table(name = "simple")
#NamedQueries({
#NamedQuery(name="SimpleObject.findAll",query = "SELECT c FROM Simple c"),
#NamedQuery(name="SimpleObject.findById" , query = "SELECT c FROM Simple c where c.id = :id")
})
public class SimpleObject {
private Long id;
private String word;
#Id
#Column(name = "ID")
public long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "WORD")
public String getWord(){
return word;
}
public void setWord(String word){
this.word = word;
}
public String toString(){
return "ID: " + id + " WORD: " + word ;
}
}
SimpleObjectImpl class that performs data operations on simpleObject
package lt.tomas.proSpring3;
import java.util.List;
import javax.persistence.*;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service("jpaSimpleService")
#Repository
#Transactional
public class SimpleObjectImpl{
#PersistenceContext(unitName="emf")
private EntityManager em;
#Transactional(readOnly=true)
public List<SimpleObject> findAll(){
return em.createNamedQuery("SimpleObject.findAll", SimpleObject.class).getResultList();
}
#Transactional(readOnly=true)
public SimpleObject findById(Long id){
TypedQuery<SimpleObject> tq = em.createNamedQuery("SimpleObject.findById", SimpleObject.class);
tq.setParameter("ID", id);
return tq.getSingleResult();
}
public void save(SimpleObject s) {
em.persist(s);
}
public void update(SimpleObject s){
em.merge(s);
}
public void Delete(SimpleObject c) {
// TODO Auto-generated method stub
}
}
A class to test it all
package lt.tomas.proSpring3;
import java.util.List;
import org.springframework.context.support.GenericXmlApplicationContext;
public class JPATest {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("app-context.xml");
ctx.refresh();
SimpleObjectImpl si = ctx.getBean("jpaSimpleService", SimpleObjectImpl.class);
List<SimpleObject> objects = si.findAll();
for(SimpleObject obj : objects){
System.out.println(obj);
}
}
}
Context config.xml file
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName">
<value>${jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<context:property-placeholder location="jdbc.properties"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="lt.tomas.proSpring3" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<context:annotation-config />
<context:component-scan base-package="lt.tomas.proSpring3"/>
</beans>
And the exception
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [app-context.xml]: Cannot resolve reference to bean 'emf' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emf' defined in class path resource [app-context.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at lt.tomas.proSpring3.JPATest.main(JPATest.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emf' defined in class path resource [app-context.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
... 13 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:257)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 20 more
Caused by: org.hibernate.HibernateException: Errors in named queries: SimpleObject.findById, SimpleObject.findAll
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:426)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)
... 25 more
Can you tell me why is this exception comming up and waht am i doing wrong? Thank you in advance.
JPA NamedQuery doesn't allow you to do a select on a DB table, instead use the Entity class name instead (case sensitive).
So, change a SELECT c from Simple c to SELECT c to SimpleObject c
So here is the correct answers:
#NamedQuery(name="SimpleObject.findAll",query = "SELECT c FROM SimpleObject c"),
#NamedQuery(name="SimpleObject.findById" , query = "SELECT c FROM SimpleObject c where c.id = :id")
I hope this helps.
Related
In my spring web application I am getting this error on launching my spring application
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 'transactionManager' defined in ServletContext resource [/WEB-INF/spring/data.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/data.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Unable to load class declared as <mapping class="reshetyk.alexey.diary.domain.DiaryUser"/> in the configuration:
Also I have this as a second error
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/data.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Unable to load class declared as <mapping class="reshetyk.alexey.diary.domain.DiaryUser"/> in the configuration:
The class DiaryUser is defined in the package and have the following properties assuming the getters and setters are well defined
this is the complete code of my entity class for DiaryUser class.java
#Entity
#Table(name = "USERS")
public class DiaryUser implements Serializable {
#Id
#Column(name = "ID_USER")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "LOGIN", unique = true, nullable = false)
private String login;
#Column(name = "PASSWORD", nullable = false)
private String password;
public DiaryUser() {
}
public DiaryUser(Integer id) {
this.id = id;
}
public DiaryUser(String login) {
this.login = login;
}
public DiaryUser(Integer id, String login, String password) {
this.id = id;
this.login = login;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I have equally defined this in my hibernate.cfg.xml file
<hibernate-configuration>
<session-factory>
<mapping class="reshetyk.alexey.diary.domain.DiaryUser" />
<mapping class="reshetyk.alexey.diary.domain.DiaryCategory" />
<mapping class="reshetyk.alexey.diary.domain.DiaryRecord" />
</session-factory>
</hibernate-configuration>
this is my data.xml file that contains my database definition configuration for hibernate mappings
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
I am kind of confused as I dont know why I am getting this error?
Instead of using LocalSessionFactoryBean,try using the AnnotationSessionFactoryBean instead and specify the mapping classes as shown below(check the link:AnnotationSessionFactoryBean)
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>test.package.Foo</value>
<value>test.package.Bar</value>
</list>
</property>
</bean>
or
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="test.package"/>
</bean>
instead of defining the mappings under hibernate.cfg.xml.
Your sessionFactory details in data.xml file can be modified as below:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--<property name="configLocation" value="classpath:hibernate.cfg.xml"/>-->
<property name="annotatedClasses">
<list>
<value>reshetyk.alexey.diary.domain.DiaryUser</value>
<value>reshetyk.alexey.diary.domain.DiaryCategory</value>
<value>reshetyk.alexey.diary.domain.DiaryRecord</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
Please make sure that mapping resource is correctly defined.
When i run my project then I am getting error
hibernate.dialect must be set when no Connection available
with this stack trace
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-dispatcher-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: 'hibernate.dialect' must be set when no Connection available
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:241)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
java.lang.Thread.run(Thread.java:722)
I am not able to understand from where this error is coming. my servlet.xml is
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.csc.StudentAdmission" />
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean id="viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name ="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/hibernatedb;create=true" />
<property name="username" value="postgres" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.csc.StudentAdmission"></property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
</props>
</property>
</bean>
</beans>
my DAo file is
package com.csc.student.DAO;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.csc.StudentAdmission.Student;
public class StudentInfo {
#Autowired
SessionFactory sessionFactory;
public StudentInfo(){
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public boolean saveStudentInfoIntoDB(Student student){
Session session = getSessionFactory().openSession();
session.beginTransaction();
String hql = "FROM Student WHERE userName='" + student.getUserName()+ "' or rollNo='" + student.getRollNo() + "'";
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<Student> results = query.list();
if (!results.isEmpty()) {
return false;
}
session.save(student);
session.getTransaction().commit();
// closing the session
session.close();
return true;
}
public Student processLoginForm(String userName, String password){
Session session = getSessionFactory().openSession();
session.beginTransaction();
String hql = "FROM Student WHERE userName='"+userName+"' and password='"+password+"'";
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<Student> results = query.list();
if(!results.isEmpty()){
Student student = new Student();
student =results.get(0);
System.out.println(student.getFirstName());
return student;
}
else
return null;
}
}
Entity name is also Student. Hence there is no fault in table name. but still this problem is coming. Can Someone solve my problem.
The configuration contains the following property.
<prop key="dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
However dialect isn't recognized by hibernate, the property hibernate.dialect is the one you are looking for.
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
For a full list of available properties check the AvailableSettings class from hibernate.
I am trying to configure springs3 for Hibernate3 annotations. I am getting following error.
I dubugged my application. its giving this exception while creating User object in getData().
Exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
java.lang.NullPointerException
com.controller.userDAO.getdata(userDAO.java:32)
com.controller.MyController.userDetail(MyController.java:32)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Here is my application-context.xml
<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/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="DataSource" ref="DataSource"/>
<property name="packagesToScan" value="com.hibernate.models" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
DAO:
#Repository
public class userDAO {
#Autowired
private SessionFactory sessionFactory;
public SessionFactory getSession() {
return sessionFactory;
}
public void setSession(SessionFactory session) {
this.sessionFactory = session;
}
#Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
public int getdata() {
String hql = "select count(*) from User";
User u = (User) getSession().openSession().createQuery(hql).uniqueResult();
return 1;
}
}
Controller:
#Controller
public class MyController {
#RequestMapping(value = "/{x}/hi", params = {"a"})
public ModelAndView add(#RequestParam(value = "a") int na, #PathVariable int x) {
System.out.println("print in console");
ModelAndView mv = new ModelAndView("demo", "message", "Add method called for na and x :" + na + "+" + na + "=" + (na + na + x));
System.out.println("obj created");
return mv;
}
#RequestMapping("/user")
public ModelAndView userDetail() {
userDAO u = new userDAO();
int x;
x = u.getdata();
ModelAndView mv = new ModelAndView("demo", "message", "rows: "+x);
return mv;
}
}
User bean for user table:
#Entity
#Table(name="user",catalog="test")
public class User implements java.io.Serializable {
private Integer id;
private String name;
private int mobile;
public User() {
}
public User(String name, int mobile) {
this.name = name;
this.mobile = mobile;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="id", unique=true, nullable=false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="name", nullable=false, length=20)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="mobile", nullable=false)
public int getMobile() {
return this.mobile;
}
public void setMobile(int mobile) {
this.mobile = mobile;
}
}
dispatcher-servlet.xml:
<!-- Scan only for #Controllers -->
<context:component-scan base-package="com.controller" use-default-filters="false" >
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<mvc:annotation-driven />
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
after annoting the user dao object in controller with Autowired annottation its giving following exception (UserDao and controller are in different packages) :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping#0' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.userDAO com.controller.MyController.u; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.dao.userDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.userDAO com.controller.MyController.u; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.dao.userDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.userDAO com.controller.MyController.u; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.dao.userDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.dao.userDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
Spring can only process an object it created. It can't inject other beans into instances it doesn't manage.
That's what you're doing here
userDAO u = new userDAO();
You're creating it yourself, so Spring know nothing about it and doesn't inject this field
#Autowired
private SessionFactory sessionFactory;
Instead, autowire the userDao bean into your #Controller class.
#Autowired
private userDao userDao;
and use that.
check your application-context.xml, bean definition sessionFactory, property name DataSource. First letter should be simple dataSource .
try with <property name="dataSource" ref="DataSource"/>
So I'm trying to implement Spring Framework and Hibernate to my web project.
I got hibernate to work at one point (register user and add it to database), but after some time nothing is working.
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Sat Jul 20 22:45:19 EET 2013]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from ServletContext resource [/WEB-INF/jdbc.properties]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7b4dab69: defining beans [messageSource,propertyConfigurer,dataSource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager]; root of factory hierarchy
WARN : org.hibernate.internal.util.xml.DTDEntityResolver - HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7b4dab69: defining beans [messageSource,propertyConfigurer,dataSource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager]; root of factory hierarchy
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/root-context.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:608)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:134)
at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:130)
at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at org.hibernate.mapping.Constraint.generateName(Constraint.java:82)
at org.hibernate.cfg.Configuration.buildUniqueKeyFromColumnNames(Configuration.java:1572)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1395)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:247)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:373)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 22 more
and Caused by: java.lang.NullPointerException
root-context.xml
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/jdbc.properties" />
</bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.databaseurl}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.something.*" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/imdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="hibernate.connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Echo all executed SQL to stdout for debugging -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="springers.Model.Bean.UserAccount" />
<mapping class="springers.Model.Bean.Movie" />
<mapping class="springers.Model.Bean.TvShow" />
<mapping class="springers.Model.Bean.Connector_User_TvShow" />
</session-factory>
data object example:
#Entity
#Table(name = "USERS")
public class UserAccount {
private int user_pk;
private String username;
private String password;
private String e_mail;
private String country;
#Id
#GeneratedValue
#Column(name = "USER_PK")
public int getUser_pk() { return user_pk; }
#Column(name = "USERNAME", nullable = false, length = 12, unique = true)
public String getUsername() { return username; }
#Column(name = "PASSWORD", nullable = false, length = 12)
public String getPassword() { return password; }
#Column(name = "E_MAIL", nullable = false, length = 50, unique = true)
public String getE_mail() { return e_mail; }
#Column(name = "COUNTRY", nullable = false, length = 25)
public String getCountry() { return country; }
public void setUser_pk (int user_pk) { this.user_pk = user_pk; }
public void setUsername(String username) { this.username = username; }
public void setPassword(String password) { this.password = password; }
public void setCountry (String country) { this.country = country; }
public void setE_mail (String e_mail) { this.e_mail = e_mail; }
user tvshow connector bean:
#Entity
#Table(name = "USER_TVSHOW_CONNECTOR",
uniqueConstraints = #UniqueConstraint(columnNames = {"user_fk", "tvShow_fk"}))
public class Connector_User_TvShow {
private int utc_pk;
private boolean toWatch = false;
private boolean favorite = false;
private boolean reminder = false;
private UserAccount user_fk;
private TvShow tvShow_fk;
#Id
#GeneratedValue
#Column(name = "UTC_PK")
public int getUtc_pk() { return utc_pk; }
#Column(name = "TO_WATCH", nullable = false)
public boolean isToWatch() { return toWatch; }
#Column(name = "FAVOURITE", nullable = false)
public boolean isFavorite() { return favorite; }
#Column(name = "REMINDER", nullable = false)
public boolean isReminder() { return reminder; }
#OneToOne(cascade = CascadeType.ALL)
public UserAccount getUser_fk() { return user_fk; }
#OneToOne(cascade = CascadeType.ALL)
public TvShow getTvShow_fk() { return tvShow_fk; }
public void setUtc_pk (int utc_pk) { this.utc_pk = utc_pk; }
public void setToWatch (boolean toWatch) { this.toWatch = toWatch; }
public void setFavorite (boolean favorite) { this.favorite = favorite; }
public void setReminder (boolean reminder) { this.reminder = reminder; }
public void setUser_fk (UserAccount user_fk) { this.user_fk = user_fk; }
public void setTvShow_fk (TvShow tvShow_fk) { this.tvShow_fk = tvShow_fk; }
Add #JoinColumn(name="user_fk") and #JoinColumn(name="tvShow_fk") to your getUser_fk and getTvShow_fk.
I just had the same NullPointerException.
You will get this NPE if there is a typo in the column name of a #UniqueConstraint annotation
The cause of your Exception was the same one:
java.lang.NullPointerException
at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:134)
at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:130)
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:324)
at java.util.TimSort.sort(TimSort.java:189)
at java.util.TimSort.sort(TimSort.java:173)
at java.util.Arrays.sort(Arrays.java:659)
at org.hibernate.mapping.Constraint.generateName(Constraint.java:82)
at org.hibernate.cfg.Configuration.buildUniqueKeyFromColumnNames(Configuration.java:1572)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1395)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
at ...
There was a bug report for this issue. The ticket has been fixed. If you update to hibernate 4.3 or later, there will be a better exception message.
PS: but in your case it's just because you didn't specify any column name on the join annotation (see the answer of #alex).
Apologies as I'm relatively new to Spring. I have the following code...
org.assessme.com.dao.UserDAOImpl.java
#Repository
public class UserDAOImpl implements UserDAO{
#Autowired
private SessionFactory sessionFactory;
#Transactional
public User getById(Long id) {
return (User) sessionFactory.getCurrentSession().load(User.class, id);
}
}
This uses org.assessme.com.dao.UserDAO.java
public interface UserDAO {
public User getById(Long id);
}
When I try to run my program, I get...
ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory org.assessme.com.bean.UserDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1266)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5015)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5302)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
My spring.xml is...
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/db" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>org.assessme.com.entity.User</value>
</list>
</property>
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="data" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<context:component-scan base-package="org.assessme" />
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Can anyone see what I'm doing incorrectly? I'm not quite sure how to autowire the sessionFactory.
My entity class is as follows...
org.assessme.com.entity.User.java
#Entity
#Table(name = "users")
public class User {
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "email")
private String email;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "id")
private long id;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
Thanks,
I'm using this in springmvc by the way, should this be in servlet-context.xml?
Here is the relevant part of the error message:
NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory]
The problem is AnnotationSessionFactoryBean does not implement the org.hibernate.SessionFactory interface. To get one of those you need to call the buildSessionFactory method.