I am getting the exception below, and I am not sure what is the reason.
my controller
package com.attar.test.controller;
import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.attar.test.entity.Patient;
import com.attar.test.service.Patientservice;
#org.springframework.stereotype.Controller
#RequestMapping("/user")
public class Controller {
#Autowired
private Patientservice patientservice;
#InitBinder
public void initbinderprocess(WebDataBinder databinder) {
StringTrimmerEditor trimedit = new StringTrimmerEditor(true);
databinder.registerCustomEditor(String.class, trimedit);
}
#RequestMapping("/frame")
public String datauser(Model model) {
Patient theuse = new Patient();
model.addAttribute("userr", theuse);
return "user-data";
}
#RequestMapping(value = "/userdata", method = RequestMethod.POST)
public String datashow(#Valid #ModelAttribute("userr") Patient thesuer, BindingResult bindresult) {
if (!bindresult.hasErrors()) {
patientservice.savepatient(thesuer);
return "show-data";
} else {
// return "redirect:/user/frame";
return "user-data";
}
}
}
PatientDaoimpl
package com.attar.test.dao;
import javax.validation.Valid;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.attar.test.entity.Patient;
#Repository
public class PatientDaoimpl implements PatientDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void savepatient(#Valid Patient thesuer) {
Session session = sessionFactory.openSession();
session.save(thesuer);
}
}
PatientServiceimpl
package com.attar.test.service;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.attar.test.dao.PatientDao;
import com.attar.test.entity.Patient;
#Service
public class PatientServiceimpl implements Patientservice {
#Autowired
private PatientDao patientdao;
#Override
#Transactional
public void savepatient(#Valid Patient thesuer) {
patientdao.savepatient(thesuer);
}
}
my patient-entity
package com.attar.test.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "patient")
public class Patient {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#NotNull(message = "it is required")
#Column(name = "first_name")
private String first_name;
#Column(name = "last_name")
private String last_name;
#Column(name = "age")
private Integer age;
public Patient() {
}
public Patient(#NotNull(message = "it is required") String first_name, String last_name, int age) {
this.first_name = first_name;
this.last_name = last_name;
this.age = age;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
WebContent/WEB-INF/spring-mvc-demo-servlet.xml
<?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" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- <aop:aspectj-autoproxy /> -->
<!-- Add support for component scanning -->
<context:component-scan base-package="com.attar.test" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven />
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/patients?useSSL=false" />
<property name="user" value="dbuser" />
<property name="password" value="dbpassword" />
<!-- these are connection pool properties for C3P0 -->
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<mvc:resources location="/resources/" mapping="/resources/**" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="resources/messages" />
</bean>
</beans>
my error-exception
HTTP Status 500 – Internal Server Error
--------------------------------------------------------------------------------
Type Exception Report
Message Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.attar.test.entity.Patient
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.attar.test.entity.Patient
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
org.hibernate.MappingException: Unknown entity: com.attar.test.entity.Patient
org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1634)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:681)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:676)
com.attar.test.dao.PatientDaoimpl.savepatient(PatientDaoimpl.java:20)
com.attar.test.service.PatientServiceimpl.savepatient(PatientServiceimpl.java:20)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
com.sun.proxy.$Proxy89.savepatient(Unknown Source)
com.attar.test.controller.Controller.datashow(Controller.java:45)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
--------------------------------------------------------------------------------
Apache Tomcat/8.5.20
I tried to put all lib for spring and hibernate. I don't know what is the cause of the problem.
You have to adopt the property "packageToScan" in your spring-mvc-demo-servlet.xml. It should specify your entity package (com.attar.test.entity).
Related
i am facing below error:
Type Exception Report
Message Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: customer is not mapped [from customer]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: customer is not mapped [from customer]
Entity Class:
package com.luv2code.springdemo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
//#Table(schema = "web_customer_tracker", name = "customer")
#Table(name="customer")
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
public Customer() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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;
}
#Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
DAO impl:
package com.luv2code.springdemo.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.luv2code.springdemo.entity.Customer;
#Repository
public class CustomerDAOImpl implements CustomerDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Customer> getCustomers() {
//get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
//List customers = new ArrayList<Customer>();
//create a query
Query<Customer> theQuery=currentSession.createQuery("from customer", Customer.class);
//currentSession.createQuery("from Customer", Customer.class);
//execute query and get result list
List<Customer> customers=theQuery.getResultList();
// return the results
/* Customer cus1=new Customer();
cus1.setEmail("a#gmail.com");
cus1.setFirstName("Abhishek");
cus1.setId(10);
cus1.setLastName("Kumar");
customers.add(cus1); */
return customers;
}
}
XML:
<?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"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.luv2code.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC" />
<property name="user" value="springstudent" />
<property name="password" value="springstudent" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
There is a difference between the entity Customer and the relational table customer.
When you specify #Table(name="customer"), you ask your JPA implementation to use customer as table name which it is probably doing (check in your database).
When you specify createQuery("from customer", Customer.class), you ask your JPA implementation to create a JPQL query and customer is not a known entity because that's Customer or com.luv2code.springdemo.entity.Customer the entity.
I am new to spring. I was trying to integrate spring with hibernate but
I am not able to get my entity class Employee using packagesToScan, before this I tried annnotatedClasses as well that too didn't work, I also tried wildcards (com.sfb.**.*) with packagesToScan but no luck yet. FYI I am using javax.persistence.Entity so not an import issue too. Below are my spring.xml file and other along with stacktrace:
Spring.xml
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/sonoo"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="AnnotatedSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.sfb.model.*" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="employeeDao" class ="com.sfb.dao.EmployeeDaoImpl">
<property name="sessionFactory" ref="AnnotatedSessionFactory"/>
</bean>
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="employee" class="com.sfb.model.Employee">
<property name="ename" value="Javed"/>
<property name="dob">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-09-30" />
</bean>
</property>
<property name="address" ref="address"/>
</bean>
<bean id="address" class="com.sfb.model.Address">
<property name="streetno" value="23"/>
<property name="city" value="Bhilai"/>
</bean>
</beans>
TestEmp.java:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class TestEmp {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("spring.xml");
EmployeeDao empDao= (EmployeeDao)context.getBean(EmployeeDao.class);
Employee emp = (Employee)context.getBean(Employee.class);
Address addr = (Address)context.getBean(Address.class);
empDao.save(emp,addr);
}
}
Address.java:
package com.sfb.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Address {
#Id
#GeneratedValue
#Column(name="street_no")
private int streetno;
#Column(name="city")
private String city;
public int getStreetno() {
return streetno;
}
public void setStreetno(int streetno) {
this.streetno = streetno;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Employee.java:
package com.sfb.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity()
#Table(name="emp")
public class Employee {
#Column(name="e_name")
private String ename;
#Id
#GeneratedValue
#Column(name="e_id")
private int eid;
#Column(name="dob")
private Date dob;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
EmployeeDao.java:
package com.sfb.dao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public interface EmployeeDao {
public void save(Employee emp , Address addr);
}
EmployeeDaoImpl.java
package com.sfb.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class EmployeeDaoImpl implements EmployeeDao {
private SessionFactory sessionFactory;
#Override
public void save(Employee emp , Address addr) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
emp.setAddress(addr);
session.persist(emp);
tx.commit();
session.close();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Exception StackTrace:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.sfb.model.Employee
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:548)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1338)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:70)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at com.sfb.dao.EmployeeDaoImpl.save(EmployeeDaoImpl.java:20)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:19)
Please help me thanks in advance
full StackTrace of NullpointerException:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AnnotatedSessionFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:545)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:15)
Caused by: java.lang.NullPointerException
at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1127)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1112)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1400)
... 12 more
Here is an error (Employee.java):
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
mappedBy attribute should only used for inverse size of association, so it is not applicable here.
I guess you are trying to build simple unidirectional association.
It should look something like:
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="ADDRESS_ID") /* this is the name of address id column in 'emp' table*/
private Address address;
Here is almost identical example from book.
I am getting the below error while trying to call a service class
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NullPointerException
org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:431)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:417)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:255)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
com.plm.conn.model.QueueService$$EnhancerBySpringCGLIB$$9405c9f4.getAll()
com.plm.conn.hcontroller.HomeController.home(HomeController.java:67)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
My servlet-context.xml
<!-- Derby configuration -->
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName"
value="org.apache.derby.jdbc.ClientDriver" />
<beans:property name="url"
value="jdbc:derby://localhost:1527//office;create=false" />
<beans:property name="username" value="office" />
</beans:bean>
<!-- EntityManagerFactory -->
<beans:bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="jtaDataSource" ref="dataSource" />
<beans:property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<beans:property name="packagesToScan" value="com.plm.conn.model" />
</beans:bean>
<!-- Transaction adapter -->
<beans:bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<beans:property name="databasePlatform"
value="org.hibernate.dialect.DerbyDialect" />
<beans:property name="showSql" value="true" />
<beans:property name="generateDdl" value="false" />
</beans:bean>
<!-- Transaction Manager -->
<beans:bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="emf" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<beans:bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- tx:annotation-driven /-->
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.plm.conn.model" />
Service
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
#Component
#Service
public class QueueService implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory
.getLogger(QueueService.class);
#PersistenceContext
private EntityManager em;
#Transactional
public void addQueue(Queue queue) {
logger.info(" info..."+em.toString());
em.persist(queue);
}
#Transactional
public List<Queue> getAll() {
TypedQuery<Queue> query = em.createNamedQuery("Queue.findAll",
Queue.class);
logger.info(" info..." + query.getResultList());
return query.getResultList();
}
}
and my controller where i am calling the queue
package com.plm.conn.hcontroller;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.plm.conn.model.Queue;
import com.plm.conn.model.QueueService;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
#Autowired
private QueueService queueSvc;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String home(Locale locale, Model model, HttpServletRequest request,
HttpServletResponse response) {
Queue queue = new Queue();
//queue.setMsgidProd("1212121212");
//queueSvc.addQueue(queue);
logger.info(queueSvc.toString());
model.addAttribute("list", queueSvc.getAll());
return "home";
}
}
I can see some improvement needs to be done in the code.
1.Why you have annotated QueueService class with #Component,#Repository and #Service annotation all together,as per the code it contains,it should be annotated only with #Repository.
2.You have used #Transactional annotation at the class level,remove it from the individual method from this class.
3.In your servlet-context.xml file,you have below line
<context:component-scan base-package="com.plm.conn.model" />
make sure that you should have configured it correctly,it should scan the spring managed component,not your database entity,because according to your servlet-context.xml file,"com.plm.conn.model" is your entity package(see <beans:property name="packagesToScan" value="com.plm.conn.model" />)
I want to persist data without persistence.xml file. this is why I use Queue.java entity class which is in the com.plm.conn.model
I am new to the Spring I learned that we can persist the data without using persistence class. I modified servlet-context.xml as follows
<!-- Derby configuration -->
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName"
value="org.apache.derby.jdbc.ClientDriver" />
<beans:property name="url"
value="jdbc:derby://localhost:1527//plmbridge;create=false" />
<beans:property name="username" value="plmt" />
</beans:bean>
<!-- EntityManagerFactory -->
<beans:bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<beans:property name="packagesToScan" value="com.plm.conn.model" />
</beans:bean>
<!-- Transaction adapter -->
<beans:bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<beans:property name="databasePlatform"
value="org.hibernate.dialect.DerbyDialect" />
<beans:property name="showSql" value="true" />
<beans:property name="generateDdl" value="false" />
</beans:bean>
<!-- Transaction Manager -->
<beans:bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="emf" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<beans:bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- tx:annotation-driven /-->
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.plm.conn.model" />
and the Queue.java file here
package com.plm.conn.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the QUEUE database table.
*
*/
#Entity
#Table(name="QUEUE")
#NamedQuery(name="Queue.findAll", query="SELECT q FROM Queue q")
public class Queue implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.TABLE)
#Column(name="QUEUE_ID", unique=true, nullable=false)
private int queueId;
#Column(length=250)
private String container;
private long expiration;
#Column(nullable=false, length=100)
private String id;
#Lob
private byte[] msg;
#Column(name="MSGID_PROD", length=250)
private String msgidProd;
#Column(name="MSGID_SEQ")
private long msgidSeq;
private long priority;
#Column(length=250)
private String xid;
//bi-directional one-to-one association to Completedjob
#OneToOne(mappedBy="queue")
private Completedjob completedjob;
//bi-directional one-to-one association to Failedjob
#OneToOne(mappedBy="queue")
private Failedjob failedjob;
public Queue() {
}
public int getQueueId() {
return this.queueId;
}
public void setQueueId(int queueId) {
this.queueId = queueId;
}
public String getContainer() {
return this.container;
}
public void setContainer(String container) {
this.container = container;
}
public long getExpiration() {
return this.expiration;
}
public void setExpiration(long expiration) {
this.expiration = expiration;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public byte[] getMsg() {
return this.msg;
}
public void setMsg(byte[] msg) {
this.msg = msg;
}
public String getMsgidProd() {
return this.msgidProd;
}
public void setMsgidProd(String msgidProd) {
this.msgidProd = msgidProd;
}
public long getMsgidSeq() {
return this.msgidSeq;
}
public void setMsgidSeq(long msgidSeq) {
this.msgidSeq = msgidSeq;
}
public long getPriority() {
return this.priority;
}
public void setPriority(long priority) {
this.priority = priority;
}
public String getXid() {
return this.xid;
}
public void setXid(String xid) {
this.xid = xid;
}
public Completedjob getCompletedjob() {
return this.completedjob;
}
public void setCompletedjob(Completedjob completedjob) {
this.completedjob = completedjob;
}
public Failedjob getFailedjob() {
return this.failedjob;
}
public void setFailedjob(Failedjob failedjob) {
this.failedjob = failedjob;
}
}
I am able to query the tables but I cant store the data I get the error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: error performing isolated work
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
ERROR 42X05: Table/View 'HIBERNATE_SEQUENCES' does not exist.
org.apache.derby.client.am.ClientStatement.completeSqlca(Unknown Source)
org.apache.derby.client.net.NetStatementReply.parsePrepareError(Unknown Source)
org.apache.derby.client.net.NetStatementReply.parsePRPSQLSTTreply(Unknown Source)
org.apache.derby.client.net.NetStatementReply.readPrepareDescribeOutput(Unknown Source)
org.apache.derby.client.net.StatementReply.readPrepareDescribeOutput(Unknown Source)
org.apache.derby.client.net.NetStatement.readPrepareDescribeOutput_(Unknown Source)
org.apache.derby.client.am.ClientStatement.readPrepareDescribeOutput(Unknown Source)
org.apache.derby.client.am.ClientPreparedStatement.readPrepareDescribeInputOutput(Unknown Source)
org.apache.derby.client.am.ClientPreparedStatement.flowPrepareDescribeInputOutput(Unknown Source)
org.apache.derby.client.am.ClientPreparedStatement.prepare(Unknown Source)
org.apache.derby.client.am.ClientConnection.prepareStatementX(Unknown Source)
org.apache.derby.client.am.ClientConnection.prepareStatement(Unknown Source)
org.hibernate.id.MultipleHiLoPerTableGenerator.prepareStatement(MultipleHiLoPerTableGenerator.java:243)
org.hibernate.id.MultipleHiLoPerTableGenerator.access$200(MultipleHiLoPerTableGenerator.java:86)
org.hibernate.id.MultipleHiLoPerTableGenerator$1.execute(MultipleHiLoPerTableGenerator.java:159)
org.hibernate.id.MultipleHiLoPerTableGenerator$1.execute(MultipleHiLoPerTableGenerator.java:152)
org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:72)
org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:51)
org.hibernate.engine.transaction.internal.jdbc.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:74)
org.hibernate.id.MultipleHiLoPerTableGenerator$2.getNextValue(MultipleHiLoPerTableGenerator.java:221)
org.hibernate.id.enhanced.LegacyHiLoAlgorithmOptimizer.generate(LegacyHiLoAlgorithmOptimizer.java:77)
org.hibernate.id.MultipleHiLoPerTableGenerator.generate(MultipleHiLoPerTableGenerator.java:218)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:291)
com.sun.proxy.$Proxy33.persist(Unknown Source)
com.plm.conn.model.QueueService.addQueue(QueueService.java:37)
com.plm.conn.model.QueueService$$FastClassBySpringCGLIB$$6b3c7d41.invoke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
com.plm.conn.model.QueueService$$EnhancerBySpringCGLIB$$77572cff.addQueue(<generated>)
com.plm.conn.hcontroller.HomeController.home(HomeController.java:63)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I built app with Spring+Hibernate+Spring Data JPA+PostgreSQL. I have Person class referenced to Marital class at two different resources.
Person has tx_person table at database pg_land.
Marital has tx_marital table at database pg_master.
I could retrieved each other when no relationships between Person and Marital. Problem occured when I built relationships (#ManyToOne and #OneToMany) between two classes.
Test Class
package id.co.p**g.sandbox;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.domain.Page;
import id.co.p**g.land.Person;
import id.co.p**g.service.land.PersonService;
public class PersonTest {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:spring-data-app-context.xml");
ctx.load("classpath:datasource.xml");
ctx.refresh();
PersonService personService = ctx.getBean(
"springJpaPersonService", PersonService.class);
Page<Person> requests = personService.getPerson(1);
listSurveys(requests);
}
private static void listSurveys(Page<Person> requests) {
// TODO Auto-generated method stub
System.out.println("List of person");
for(Person request: requests) {
System.out.println(request);
}
}
}
Error Message
Exception in thread "main" org.springframework.data.mapping.PropertyReferenceException: No property no found for type id.co.palmagroup.land.Person
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:74)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:325)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:305)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:269)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:240)
at org.springframework.data.jpa.repository.query.QueryUtils.toJpaOrder(QueryUtils.java:427)
at org.springframework.data.jpa.repository.query.QueryUtils.toOrders(QueryUtils.java:390)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:457)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:438)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:320)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:290)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:358)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy35.findAll(Unknown Source)
at id.co.palmagroup.service.land.PersonImpl.getPerson(PersonImpl.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
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:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy39.getPerson(Unknown Source)
at id.co.palmagroup.sandbox.PersonTest.main(PersonTest.java:20)
Person Class
package id.co.p**g.land;
import id.co.p**g.master.Marital;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name = "tx_person")
public class Person {
private UUID id;
private String name;
private Marital marital;
#Id
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
#Type(type="pg-uuid")
#Column(name = "id")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
#NotEmpty(message="{validation.formcode.NotEmpty.message}")
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToOne(targetEntity=Marital.class)
#JoinColumn(name="id_marital")
#Type(type="pg-uuid")
public Marital getMarital() {
return marital;
}
public void setMarital(Marital marital) {
this.marital = marital;
}
public String toString() {
return "Person ID: " + id
+ ". Name: " + name
+ ". Marital: " + marital;
}
}
Marital Class
package id.co.p**g.master;
import id.co.p**g.land.Person;
import java.util.Set;
import java.util.UUID;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
#Entity
#Table(name = "m_marital")
public class Marital implements Serializable {
private UUID id;
private String name;
private String description;
private int no;
private Set<Person> persons;
#Id
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
#Type(type="pg-uuid")
#Column(name = "id")
public UUID getId() {
return this.id;
}
public void setId(UUID id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "description")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#OneToMany(targetEntity=Person.class, mappedBy="marital")
public Set<Person> getPersons() {
return this.persons;
}
#Column(name="no")
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public void setPersons(Set<Person> persons) {
this.persons = persons;
}
public String toString() {
return + no + ". "
+ "Marital ID: " + id
+ " Name: " + name
+ ". Description: " + description;
}
}
Person Implementation Class
package id.co.p**g.service.land;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
import id.co.p**g.land.Person;
import id.co.p**g.repository.land.PersonRepository;
#Service("springJpaPersonService")
#Repository
#Transactional
public class PersonImpl implements PersonService {
// TODO PAGE_SIZE, rubah menjadi konfigurasi parameter.
private static final int PAGE_SIZE = 10;
#Autowired
private PersonRepository personRepository;
#PersistenceContext(unitName="landPersistence")
private EntityManager em;
#Transactional(readOnly=true)
public List<Person> findAll() {
return Lists.newArrayList(personRepository.findAll());
}
public Person save(Person person) {
return personRepository.save(person);
}
public void delete(Person person) {
personRepository.delete(person);
}
#Transactional(readOnly=true)
public Person findById(UUID id) {
return personRepository.findById(id);
}
#Transactional(readOnly=true)
public Page<Person> findAllByPage(Pageable pageable) {
return personRepository.findAll(pageable);
}
#Override
public Page<Person> getPerson(Integer pagenumber) {
PageRequest pagerequest = new PageRequest(pagenumber - 1, PAGE_SIZE, Sort.Direction.ASC, "no");
return personRepository.findAll(pagerequest);
}
}
Marital Implementation Class
package id.co.p**g.service.master;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
import id.co.p**g.master.Marital;
import id.co.p**g.repository.master.MaritalRepository;
#Service("springJpaMaritalService")
#Repository
#Transactional
public class MaritalImpl implements MaritalService {
// TODO PAGE_SIZE, rubah menjadi konfigurasi parameter.
private static final int PAGE_SIZE = 10;
#Autowired
private MaritalRepository maritalRepository;
#PersistenceContext(unitName="masterPersistence")
private EntityManager em;
#Transactional(readOnly=true)
public List<Marital> findAll() {
return Lists.newArrayList(maritalRepository.findAll());
}
#Transactional(readOnly=true)
public Marital findById(UUID id) {
return maritalRepository.findById(id);
}
#Transactional(readOnly=true)
public Page<Marital> findAllByPage(Pageable pageable) {
return maritalRepository.findAll(pageable);
}
#Override
public Page<Marital> getMarital(Integer pagenumber) {
PageRequest pagerequest = new PageRequest(pagenumber - 1, PAGE_SIZE, Sort.Direction.ASC, "name");
return maritalRepository.findAll(pagerequest);
}
}
Application 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"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- LAND -->
<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="persistenceUnitName" value="landPersistence"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="id.co.p**g.*" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.PostgreSQLDialect
</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>
<!-- MASTER -->
<bean id="transactionManagerMaster" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emfMaster" />
</bean>
<tx:annotation-driven transaction-manager="transactionManagerMaster" />
<bean id="emfMaster"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="masterPersistence"/>
<property name="dataSource" ref="dataSourceMaster" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="id.co.p**g.*" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.PostgreSQLDialect
</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="id.co.p**g.service.*" />
<jpa:repositories base-package="id.co.p**g.repository.land"
entity-manager-factory-ref="emf" transaction-manager-ref="transactionManager" />
<jpa:repositories base-package="id.co.p**g.repository.master"
entity-manager-factory-ref="emfMaster" transaction-manager-ref="transactionManagerMaster" />
</beans>
Data Source Configuration 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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/pg_land" />
<property name="username" value="sysland" />
<property name="password" value="password" />
</bean>
<bean id="dataSourceMaster"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/pg_master" />
<property name="username" value="usermaster" />
<property name="password" value="password" />
</bean>
</beans>
I use different associations in different database.
Mark the relationship with # transient and just put the id of the entity.
when you will need to refer to the id of the entity at the other database. just use a find
I dont know what is wrong in my listContacts in controller
map.put("contactList", contactService.listContact());
Can somebody help me?
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/test] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at pl.ivmx.contact.controller.ContactController.listContacts(ContactController.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
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)
package pl.ivmx.contact.controller;
import java.util.Map;
import pl.ivmx.contact.dao.ContactDAO;
import pl.ivmx.contact.form.Contact;
import pl.ivmx.contact.service.ContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ContactController {
#Autowired
private ContactService contactService;
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact") Contact contact,
BindingResult result) {
contactService.addContact(contact);
return "redirect:/contact";
}
#RequestMapping("/delete/{contactId}")
public String deleteContact(#PathVariable("contactId") Integer contactId) {
contactService.removeContact(contactId);
return "redirect:/contact";
}
}
package pl.ivmx.contact.dao;
import java.util.List;
import pl.ivmx.contact.form.Contact;
public interface ContactDAO {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}
package pl.ivmx.contact.dao;
import java.util.List;
import pl.ivmx.contact.form.Contact;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class ContactDAOImpl implements ContactDAO {
#Autowired
private SessionFactory sessionFactory;
public void addContact(Contact contact) {
sessionFactory.getCurrentSession().save(contact);
}
public List<Contact> listContact() {
return sessionFactory.getCurrentSession().createQuery("from Contact").list();
}
public void removeContact(Integer id) {
Contact contact = (Contact) sessionFactory.getCurrentSession().load(
Contact.class, id);
if (null != contact) {
sessionFactory.getCurrentSession().delete(contact);
}
}
}
package pl.ivmx.contact.service;
import java.util.List;
import pl.ivmx.contact.form.Contact;
public interface ContactService {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}
package pl.ivmx.contact.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.ivmx.contact.dao.ContactDAO;
import pl.ivmx.contact.form.Contact;
#Service
public class ContactServiceImpl implements ContactService {
#Autowired
private ContactDAO contactDAO;
#Transactional
public void addContact(Contact contact) {
contactDAO.addContact(contact);
}
#Transactional
public List<Contact> listContact() {
return contactDAO.listContact();
}
#Transactional
public void removeContact(Integer id) {
contactDAO.removeContact(id);
}
}
package pl.ivmx.contact.form;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="CONTACTS")
public class Contact {
#Id
#Column(name="ID")
#GeneratedValue
private Integer id;
#Column(name="FIRSTNAME")
private String firstname;
#Column(name="LASTNAME")
private String lastname;
#Column(name="EMAIL")
private String email;
#Column(name="TELEPHONE")
private String telephone;
public String getEmail() {
return email;
}
public String getTelephone() {
return telephone;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/pages/index.jsp</welcome-file>
</welcome-file-list>
applicationContext.xml
<?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:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="pl.ivmx.contact" />
<!-- <bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="messages_en.properties" />
<property name="defaultEncoding" value="UTF-8" />
</bean> -->
<import resource="commonContext.xml" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="userTestDao" class="pl.ivmx.dao.impl.UserTestDaoImpl">
<!-- <property name="dataSource" ref="dataSource" /> -->
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
<!-- class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="META-INF/hibernate.cfg.xml" />
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<!-- <property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>pl.ivmx.model.UserTest</value>
</list>
</property> -->
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/index.do"> <ref bean="index" /></entry>
<entry key="/registration.do"> <ref bean="registration" /></entry>
<entry key="/usertestlist.do"> <ref bean="usertest" /></entry>
<entry key="/contact.do"> <ref bean="contact" /></entry>
</map>
</property>
</bean>
<bean id="index" class="pl.ivmx.web.IndexController"/>
<bean id="registrationValidator" class="pl.ivmx.validation.RegistrationValidator" />
<bean id="registration" class="pl.ivmx.web.RegistrationFormController" >
<property name="commandName"><value>userTest</value></property>
<property name="commandClass"><value>pl.ivmx.model.UserTest</value></property>
<property name="validator"><ref local="registrationValidator"/></property>
<property name="formView"><value>registration</value></property>
<property name="successView"><value>registrationsuccess</value></property>
<property name="userTestDao"><ref bean="userTestDao"/></property>
</bean>
<bean id="usertest" class="pl.ivmx.web.UserTestController">
<property name="userTestDao"><ref bean="userTestDao"/></property>
</bean>
<bean id="contact" class="pl.ivmx.contact.controller.ContactController">
</bean>
<bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl">
</bean>
<bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl">
</bean>
</beans>
It looks like a NullPointerException thrown in the method here:
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact";
}
I would debug and check that contactService has been autowired correctly.
The null pointer is line 26, if that is the line containing contactService.listContact() then contactService is null. If it is the line above then the map is null.
I am not sure but try adding:
<context:component-scan base-package="pl.ivmx.contact" />
to the dispatcher-servlet.xml as well, it could be that the annotation isnt getting processed
you are returning "/contact" there in the method as a view to be shown:
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact"; // <---- here!
}
This means that you should have a view named /contact defined somewhere, but I don't see it. You need to have a view that corresponds with the value you're defining.
You probably want to return a value like "contact" instead of "/contact" and then have contact.jsp in the webapp/WEB-INF/views folder (assuming you use maven standard directory layout).
I don't see anything obvious ... could sessionFactory be null? Should be easy to find, tho. Step through the code in the debugger.
I think you are missing to add the contactService bean to your applicationContext.xml
try adding the below to tags
<bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl">
<property name="contactDAO" ref="contactDAO" />
</bean>
<bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl" />