Not able to use injected properties in spring beans - java

below is my spring-database.xml file. I can use sessionFactory in userDao. I also can use userDao in myUserDetailsService class. but when i try to use sessionFactory in registrationDao it gives me NullPointerException. same happens when i try to use registrationDao in registrationService service.
i am getting confused. please help.
<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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.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/myds" />
<property name="username" value="root" />
<property name="password" value="mypass" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.findsuvidha.web.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="userDao" class="com.findsuvidha.web.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="myUserDetailsService" class="com.findsuvidha.web.service.MyUserDetailsService">
<property name="userDao" ref="userDao" />
</bean>
<bean id="registrationDao" class="com.findsuvidha.web.dao.RegistrationDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="registrationService" class="com.findsuvidha.web.service.RegistrationService">
<property name="registrationDao" ref="registrationDao" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="userServicePointCut"
expression="execution(* com.findsuvidha.web.service.*Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut" />
</aop:config>
</beans>
Edit1:-Dao and DaoImpl which are able to use injected property
UserDao.java
package com.findsuvidha.web.dao;
import com.findsuvidha.web.entity.LoginMaster;
public interface UserDao {
LoginMaster findByUserName(String username);
}
UserDaoImpl.java
package com.findsuvidha.web.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import com.findsuvidha.web.entity.LoginMaster;
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public LoginMaster findByUserName(String email) {
List<LoginMaster> users = new ArrayList<LoginMaster>();
users = getSessionFactory().getCurrentSession().createQuery("from LoginMaster where email=?")
.setParameter(0, email).list();
if (users.size() > 0) {
return users.get(0);
} else {
return null;
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Dao and DaoImpl which are not able to use injected property
RegistrationDao.java
package com.findsuvidha.web.dao;
import com.findsuvidha.web.transferobject.NewUser;
public interface RegistrationDao {
void insertUser(NewUser user);
}
RegistrationDaoImpl.java
package com.findsuvidha.web.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.findsuvidha.web.entity.LoginMaster;
import com.findsuvidha.web.entity.UserDetail;
import com.findsuvidha.web.transferobject.NewUser;
public class RegistrationDaoImpl implements RegistrationDao{
private SessionFactory sessionFactory;
private LoginMaster loginUser = new LoginMaster();
private UserDetail userDetail = new UserDetail();
#Override
public void insertUser(NewUser user) {
System.out.println("entered dao impl");
userDetail.setEmail(user.getEmail());
userDetail.setFirstName(user.getFirstName());
userDetail.setLastName(user.getLastName());
userDetail.setMobileNo(user.getMobileNumber());
loginUser.setEmail(user.getEmail());
loginUser.setPassword(user.getPassword());
loginUser.setRoleFlag("ROLE_USR");
loginUser.setUserDetail(userDetail);
System.out.println("before session save");
getSessionFactory().getCurrentSession().save(loginUser);
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}

Related

hibernate can't save data

when i use hibernate to save entity i found that session can't save it in Transaction. i must flush and clear session.but i have not to do like this before in other projects,is there anything wrong with the transaction configs in my xml files?Any answers are appreciated : )
hibernate.cfg.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: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/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">
<context:property-placeholder location="classpath:application.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${db.userName}"></property>
<property name="password" value="${db.password}"></property>
</bean>
<bean id="sessionFactory" name="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<!--<prop key="current_session_context_class">thread</prop>-->
</props>
</property>
<property name="packagesToScan" value="com.gtis"/>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--<bean id="transactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,-myException</prop>
<prop key="del*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>-->
<!--<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="import*" propagation="REQUIRED" />
<tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="serviceOperation" expression="execution(* com.gtis.service.*Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>-->
</beans>
Dao
package com.gtis.dao;
import com.gtis.model.Student;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by u on 2016/3/15.
*/
#Repository
public class StudentDao {
#Resource
private SessionFactory sessionFactory;
private Session getSession(){
return sessionFactory.getCurrentSession();
}
public Student query(String id) throws Exception{
if(StringUtils.isBlank(id)){
return (Student)getSession().get(Student.class,id);
}else{
throw new Exception("id is required");
}
}
public List<Student> queryAll(){
String hql = "from com.gtis.model.Student";
Query query = getSession().createQuery(hql);
return query.list();
}
public void save(Student student)throws Exception{
if(student!=null){
System.out.println("sessionFactory="+sessionFactory);
System.out.println("session="+getSession());
// Session session = getSession();
getSession().save(student);
// session.flush();
// session.clear();
// session.close();
}else{
throw new Exception("object is required");
}
}
public void delete(Student student)throws Exception{
if(student!=null){
getSession().delete(student);
}else{
throw new Exception("object is required");
}
}
}
Service
package com.gtis.service;
import com.gtis.dao.StudentDao;
import com.gtis.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by u on 2016/3/15.
*/
#Service
public class StudentService {
#Autowired
StudentDao studentDao;
public Student getStudent(String id) throws Exception {
return studentDao.query(id);
}
public List<Student> getAll() throws Exception{
return studentDao.queryAll();
}
#Transactional
public void save(Student student)throws Exception{
studentDao.save(student);
}
#Transactional
public void delete(Student student) throws Exception{
studentDao.delete(student);
}
}
> Controller
package com.gtis.controller;
import com.gtis.model.Student;
import com.gtis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by u on 2016/3/15.
*/
#Controller
public class StudentController {
#Autowired
StudentService studentService;
#RequestMapping("get")
public String get(){
Student student = new Student();
student.setName("avc");
try {
studentService.save(student);
} catch (Exception e) {
e.printStackTrace();
}
return "somwhere";
}
}
Your DAO should implement an interface and inject that interface via Autowired to your Service which uses the #Transactional annotation in order to work.
So:
#Repository
public class StudentDao implements StudentDaoInterface {
//your rest code here
}
And:
#Service
public class StudentService {
#Autowired
StudentDaoInterface studentDao;
public Student getStudent(String id) throws Exception {
return studentDao.query(id);
}
public List<Student> getAll() throws Exception{
return studentDao.queryAll();
}
#Transactional
public void save(Student student)throws Exception{
studentDao.save(student);
}
#Transactional
public void delete(Student student) throws Exception{
studentDao.delete(student);
}
}
And of course dont forget to declare your public methods of your DAO to the interface.
Oh and do the same for your Service class (interface, autowire the interface instead of the class etc).
You should Autowired the sessionfactory to give spring a full control to commit your transactions.

No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined"}}

I'm having problem with my web-app, cannot deploy the project to WildFly.
Problem:
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookedRoomDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:222)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
... 3 more
Here is my application-context.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>text_resources</value>
</list>
</property>
</bean>
<bean name="exceptionResolver" class="com.booking.common.HotelException" autowire="byName">
<property name="exceptionMappings">
<props>
<prop key="javax.servlet.jsp.JspException">exception</prop>
<prop key="javax.servlet.ServletException">exception</prop>
<prop key="java.lang.Exception">exception</prop>
<prop key="java.lang.Throwable">exception</prop>
<prop key="java.lang.RuntimeException">exception</prop>
<prop key="org.springframework.web.bind.ServletRequestBindingException">exception</prop>
</props>
</property>
</bean>
<bean id="mailSession" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:jboss/mail/Default"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/booking-war"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="true" autowire="default">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.booking.member.vo" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<context:component-scan base-package="com.booking.dao" />
<context:component-scan base-package="com.booking.member" />
<context:component-scan base-package="com.booking.service" />
</beans>
UserDaoImpl.java
package com.booking.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.booking.dao.GenericDao;
import com.booking.dao.UserDao;
import com.booking.member.vo.AuthenticateUser;
#Repository("userDao")
public class UserDaoImpl implements UserDao{
#Autowired
GenericDao<AuthenticateUser,Long> genericDao;
#PersistenceContext
EntityManager entityManager;
#Override
public List<AuthenticateUser> userByName(String username) {
String queryStr = "SELECT u FROM AuthenticateUser u WHERE u.username= ? ";
return entityManager.createQuery(queryStr)
.setParameter(1,username).getResultList();
}
public AuthenticateUser create(AuthenticateUser t) {
return genericDao.create(t);
}
public AuthenticateUser read(Long id, Class<AuthenticateUser> c) {
return genericDao.read(id, c);
}
public AuthenticateUser update(AuthenticateUser t) {
return genericDao.update(t);
}
public void delete(AuthenticateUser t) {
genericDao.delete(t);
}
public List<AuthenticateUser> getAll(Class<AuthenticateUser> c) {
return genericDao.getAll(c);
}
}
GenericDaoImpl.java :
package com.booking.dao.impl;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.ejb.HibernateEntityManager;
import org.springframework.stereotype.Repository;
import com.booking.dao.GenericDao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
#Repository("genericDao")
public class GenericDaoImpl<T,PK extends Serializable> implements GenericDao<T, PK> {
protected Class<T> entityClass;
#PersistenceContext
protected EntityManager entityManager;
#Override
public T create(T t) {
this.entityManager.persist(t);
return t;
}
#Override
public T read(PK id,Class<T> c) {
return (T)this.entityManager.find(c, id);
}
#Override
public T update(T t) {
return this.entityManager.merge(t);
}
#Override
public void delete(T t) {
t = this.entityManager.merge(t);
this.entityManager.remove(t);
}
#Override
public List<T> getAll(Class<T> c){
return this.entityManager.createQuery("SELECT o FROM "+ c.getName() +" o").getResultList();
}
#Override
public List<T> getByFilter(T filter){
Session session = ((HibernateEntityManager)entityManager.unwrap(HibernateEntityManager.class)).getSession();
return session.createCriteria(filter.getClass()).add(Example.create(filter)).list();
}
}
BookedRoomDaoImpl.java :
package com.booking.dao.impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.booking.common.CommonUtils;
import com.booking.dao.BookedRoomDao;
import com.booking.dao.GenericDao;
import com.booking.member.vo.BookedRoom;
import com.booking.member.vo.Booking;
import com.booking.member.vo.TimeRange;
import org.hibernate.criterion.Restrictions;
#Repository("bookedRoomDao")
public class BookedRoomDaoImpl implements BookedRoomDao{
#PersistenceContext
EntityManager entityManager;
#Autowired
GenericDao<TimeRange,Long> timeRangeDao;
#Override
public List<BookedRoom> getBookedRooms(long id,String date){
List<BookedRoom> list = new ArrayList<BookedRoom>();
List<TimeRange> timeRanges = timeRangeDao.getAll(TimeRange.class);
for(TimeRange timeRange:timeRanges){
BookedRoom bookedRoom = new BookedRoom();
Booking booking = null;
try{
booking = (Booking)entityManager.createNativeQuery("select * from Booking b where b.time_range = ?1 and b.room = ?2 and date_format(date_booked,'%Y-%m-%d') = ?3",Booking.class)
.setParameter(1,timeRange.getId())
.setParameter(2,id)
.setParameter(3,date)
.getSingleResult();
}catch (NoResultException e) {
}
if(booking!=null){
bookedRoom.setBookingId(booking.getBookingId());
bookedRoom.setDateBooked(booking.getDateBooked());
bookedRoom.setRoomName(booking.getRoom().getRoomName());
bookedRoom.setUserName(booking.getUserid().getUsername());
if(booking.getUserid().getId()==CommonUtils.getCurrentUserProfile().getUserId()){
bookedRoom.setOwner(true);
}
}
bookedRoom.setFromTime(timeRange.getFromTime());
bookedRoom.setToTime(timeRange.getToTime());
bookedRoom.setTrId(timeRange.getId());
list.add(bookedRoom);
}
return list;
}
#Override
public void deleteBooking(long bookingId,long userId){
entityManager.createNativeQuery("delete from booking where booking_id=?1 and userid=?2")
.setParameter(1, bookingId)
.setParameter(2,userId)
.executeUpdate();
}
#Override
public List getBookingByRoomId(long roomId){
return entityManager.createNativeQuery("select * from booking where room = ?1",Booking.class)
.setParameter(1, roomId)
.getResultList();
}
}
And hibernate.cfg.xml :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<validation-mode>NONE</validation-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<!--value='create' to build a new database on each run; value='update' to modify an existing database; value='create-drop' means the same as 'create' but also drops tables when Hibernate closes; value='validate' makes no changes to the database-->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.ejb.cfgfile" value="/resources/hibernate/hibernate.cfg.xml"/>
</properties>
</persistence-unit>
</persistence>
You need to add entityManagerFactory like this:
<bean id="entityManagerFactory" 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="jpaProperties" ref="hibernatePropertiesBean"/>
<property name="packagesToScan">
<list>
<value>your.packages</value>
</list>
</property>
</bean>

Hibernate & Spring: EntityManager is Null

I'm setting up a Project with Spring and Hibernate. I created an abstract DAO class that contains an EntityManager. When I want to use this EntityManager, it's null and I dont understand why. Maybe you can help me.
My persistence-context
<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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
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.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<import resource="persistence-beans.xml" />
<mvc:annotation-driven />
<bean id="jdbcPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:META-INF/mysql.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${hibernate.show_sql}" />
<property name="generateDdl" value="${hibernate.generate_ddl}" />
<property name="databasePlatform" value="${hibernate.dialect}" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="personDao" class="com.patrickzinner.dao.PersonDao" />
<tx:annotation-driven transaction-manager="transactionManager" />
PersonDao.java:
#Repository
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class PersonDao extends AbstractDao<Person> {
public PersonDao() {
super(Person.class);
}
}
AbstractDao.java
#SuppressWarnings("unchecked")
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public abstract class AbstractDao<T> {
#PersistenceContext
protected EntityManager em;
private Class<T> entityClass;
public AbstractDao(Class<T> entityClass) {
this.entityClass = entityClass;
}
public AbstractDao() {
}
public void create(T entity) {
this.em.persist(entity);
}
public void edit(T entity) {
this.em.merge(entity);
}
public void remove(T entity) {
this.em.remove(this.em.merge(entity));
}
public T find(long primaryKey) {
return this.em.find(entityClass, primaryKey);
}
#SuppressWarnings("rawtypes")
public List<T> findAll() {
CriteriaQuery cq = this.em.getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return this.em.createQuery(cq).getResultList();
}
}
Thanks in advance!
An entity manager can only be injected in transaction classes. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.
but your AbstractDAO is not EJB you can not use EntityManager directly.
solution
#PersistenceUnit(unitName = "test")
private EntityManagerFactory entityManagerFactory;
EntityManager entityManager = entityManagerFactory.createEntityManager();
then perform operation using emtityManager.
alternatively you can use container managed Transaction using JNDI lookup..
let me know for any issues.
Try adding <context:annotation-config /> to your persistence-context. This section of the reference manual may help you to use #PersistenceContext.

Getting java.lang.NullPointerException while getSession().save(entity);

I want to add object data and want to save in DB table, everything working fine but it gives me an error :
java.lang.NullPointerException
on line getSession().save(entity);
I have called this method in code :
#Service
public class AddCategoryProcessor implements ICommandProcessor<AddCategory> {
#Autowired
private IPatronCategoryRepository patronCategoryRepository = new PatronCategoryRepository();
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
patronCategoryRepository.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
}
following is my xml file :
<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/abc"/>
<property name="username" value="postgres"/>
<property name="password" value="pwd"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.ngl.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
Here is a getSession() method :
#Override
public Session getSession() {
return getSessionFactory().getCurrentSession();
}
Here is a sessionFactory declaration :
protected SessionFactory sessionFactory;
Any guesses why it's NULLPOINTEREXCEPTION ??
UPDATE :
java.lang.NullPointerException
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:32)
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:16)
at com.ngl.controllerapis.BaseApiController.ProcessRequest(BaseApiController.java:29)
at com.ngl.controllerapis.PatronCategoryController.addCategory(PatronCategoryController.java:39)
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.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
and xml for transaction manager
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
in repository
#Autowired
protected SessionFactory sessionFactory;
Your config is a bit incomplete. You should delegate session management completely to Spring
Add in you spring xml file:
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Then, in your PatronCategoryRepository class, extend HibernateDaoSupport and add this constructor:
public class PatronCategoryRepository extends HibernateDaoSupport implements IPatronCategoryRepository{
#Autowired
public PatronCategoryRepository(HibernateTemplate hibernateTemplate) {
super();
super.setHibernateTemplate(hibernateTemplate);
}
[...]
}
In AddCategoryProcessor, leave the definition of the repository like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
And finally your method:
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
getHibernateTemplate.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
In case you still need to access directy the SessionFactory, the only thing you have to do is inject it into PatronCategoryRepository:
#Repository
public class PatronCategoryRepository implements IPatronCategoryRepository{
#Autowired
protected SessionFactory sessionFactory;
public PatronCategoryRepository() {
}
public PatronCategory save(PatronCategory entity){
return getSession().save(entity);
}
private Session getSession() {
return sessionFactory.getCurrentSession();
}
}
And remember to remove the new clause from AddCategoryProcessor, leaving it like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
Employee.java
package com.javacodegeeks.snippets.enterprise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Employee1")
public class Employee implements Serializable {
#Id
#Column(name = "ID")
private int id;
#Column(name = "NAME")
private String name;
#Column(name = "AGE")
private int age;
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
EmployeeDao.java
package com.javacodegeeks.snippets.enterprise.dao;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public interface EmployeeDAO {
public void saveEmployee(Employee employee);
Employee findEmployeeById(int id);
void updateEmployee(Employee employee);
void deleteEmployee(Employee employee);
}
EmployeeDaoImpl.java
package com.javacodegeeks.snippets.enterprise.dao;
import java.io.Serializable;
import org.hibernate.SessionException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public class EmployeeDAOImpl implements EmployeeDAO {
private HibernateTemplate template;
private SessionFactory sessionFactory;
#Autowired
public void setTemplate(HibernateTemplate template) {
this.template = template;
// template.setSessionFactory(sessionFactory);
}
public void setSessionFactory(SessionFactory sessionFactory) {
new HibernateTemplate(sessionFactory);
}
/*
* public void saveEmployee(Employee employee) {
* sessionFactory.getCurrentSession().save(employee);
*
* }
*/
public Employee findEmployeeById(int id) {
return (Employee) sessionFactory.getCurrentSession().get(
Employee.class, id);
}
public void updateEmployee(Employee employee) {
sessionFactory.getCurrentSession().update(employee);
}
public void deleteEmployee(Employee employee) {
sessionFactory.getCurrentSession().delete(employee);
}
public void saveEmployee(Employee employee) {
sessionFactory.getCurrentSession().persist(employee);
template.saveOrUpdate(employee);
}
}
Application COntext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="com.javacodegeeks.snippets.enterprise.*" />
<!-- <tx:annotation-driven/> -->
<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/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.javacodegeeks.snippets.enterprise.model.Employee</value>
</list>
</property>
<!-- <property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property> -->
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> -->
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="d" class="com.javacodegeeks.snippets.enterprise.dao.EmployeeDAOImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
pleas ehelp me :-)

What is a solution develop correctly this Spring and JPA webapp example?

I have a Controller for my webapp developed with Spring mvc under Maven 3. In this controller I've #Autowired
PersonDAO dbController
I want to use JPA 2.0 to manage persistance so I rewrited my applicationContext.xml:
I added
`<tx:annotation-driven transaction-manager="transactionManager" />
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="dataSource" ref="dataSource" />
<!-- <property name="packagesToScan" value="net.tirasa.test.addressbook.dao" />-->
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<!--<property name="generateDdl" value="true" />-->
<!--<property name="databasePlatform" value="org.hibernate.dialect.H2Dialect" />-->
<!--<property name="database" value="H2" />-->
</bean>
</property>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>`
and my PersonDAOImpl is:
#Repository
public class PersonDAOJpaImpl implements PersonDAO {
//#Value("#{entityManager}")
#PersistenceContext(type = PersistenceContextType.TRANSACTION)
//#Autowired
protected EntityManager entityManager;
private final static Logger LOG = LoggerFactory.getLogger(PersonDAOJpaImpl.class);
#Transactional
public void save(String id, String name, String email, String telephone) throws DatabaseException {
Person person = null;
if (find(id) == null) {
entityManager.persist(person);
} else {
entityManager.merge(person);
}
}
#Transactional
public Person find(String requestParam_id) throws DatabaseException {
return entityManager.find(Person.class, requestParam_id);
}
#Transactional
public List<Person> list() throws DatabaseException {
Query query = entityManager.createQuery("select p from Persons p");
List<Person> resultList = query.getResultList();
Person p = null;
entityManager.find(Person.class, "Andrea Patricelli");
System.out.println("ECCO UN ELEMENTO DELLA LISTA: ------->" + resultList.iterator().next().getName());
System.out.println("ECCO IL RISULTATO DELLA FIND: -------->" + p.getName());
return resultList;
}
but nothing works;
what do I do wrong?
In particular I don't know how to connect My PersonDAO dbController with PersonDAOImpl and with entityManager
To start off your packages to scan is not setup correctly for the entityManagerFactory. You are scanning your dao's there when you should be scanning your model/domain(Classes with #Entity on them).

Categories