LazyLoadInit exception with Spring + Spring JPA data + hibernate - spring

I can't figure this out. Am getting "Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.sandy.domain.Location.items, no session or session was closed"
I understand that session is closed but tx:annotation-driver #Transactional should ensure an open session. It works fine with EAGER fetching. Oh and yea - this is by apress pro spring 3 examples.
But maybe I don't get the concept here - I mean while I am debugging "getFirst()" in SomeService I can see all the items in the collection but once return hits - LazyInit exception is thrown...
package org.sandy.main;
import org.sandy.domain.Item;
import org.sandy.domain.Location;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Service;
#Service(value = "main")
public class EntryPoint {
#Autowired
private SomeService ss;
public static void main(String args[]) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:*-beans.xml");
ctx.refresh();
EntryPoint entryPoint = (EntryPoint) ctx.getBean("main");
Item item = new Item();
Location location = new Location();
item.setLocation(location);
location.getItems().add(item);
entryPoint.getSs().save(location);
System.out.println(entryPoint.getSs().findFirst());
ctx.registerShutdownHook();
}
public SomeService getSs() {
return ss;
}
public void setSs(SomeService ss) {
this.ss = ss;
}
}
and the service
package org.sandy.main;
import org.sandy.domain.Item;
import org.sandy.domain.Location;
import org.sandy.repo.ItemRepo;
import org.sandy.repo.LocationRepo;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service(value = "ss")
#Repository
#Transactional
public class SomeService {
#Autowired
private ItemRepo itemRepo;
#Autowired
private LocationRepo locationRepo;
#Transactional
public void save(Location location) {
locationRepo.save(location);
}
#Transactional(readOnly = true)
public List<Item> findFirst() {
System.out.println("ONE");
Iterable<Location> it = locationRepo.findAll();
System.out.println("TWO");
Location l = it.iterator().next();
System.out.println("THREE");
List<Item> r = l.getItems();
return r;
}
#Transactional
public Iterable finAll() {
return locationRepo.findAll();
}
public void setItemRepo(ItemRepo itemRepo) {
this.itemRepo = itemRepo;
}
public void setLocationRepo(LocationRepo locationRepo) {
this.locationRepo = locationRepo;
}
}
and location repo
package org.sandy.repo;
import org.sandy.domain.Location;
import org.springframework.data.repository.CrudRepository;
public interface LocationRepo extends CrudRepository<Location, Long> {
}
Entities:
#Entity
#Table(name = "Locations")
public class Location extends Entry {
private List<Item> items = new ArrayList<Item>();
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "location")
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
package org.sandy.domain;
import javax.persistence.*;
#Entity
#Table(name = "Items")
public class Item extends Entry {
private Location location;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn()
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
And the all mighty xml bean config:
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
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.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<jdbc:embedded-database id="dataSource" type="H2" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="org.sandy.domain" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.H2Dialect
</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>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
</bean>
<context:annotation-config/>
<jpa:repositories base-package="org.sandy.repo" entity-manager-factory-ref="emf" transaction-manager-ref="transactionManager" />
<context:component-scan base-package="org.sandy" />
</beans>

This piece of code
System.out.println(entryPoint.getSs().findFirst());
is equivalent to
/* 1 */ SomeService ss = entryPoint.getSs();
/* 2 */ List<Item> items = ss.findFirst(); // Session opens and closes for #Transactional
/* 3 */ String toPrint = items.toString(); // no more Session
/* 4 */ System.out.println(toPrint);
So you can see that the Session boundary is only wrapping the findFirst() call. If you're loading your entities lazily, then on line 3, the elements in items are not initialized. When you try to call toString() inside List#toString() which calls toString() on each element, you will get your LazyInitializationException.
You should fully initialize your entities before you use them. That has to be done within Session boundaries.

Related

autowired dao NullPointerException spring mvc + hibernate [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 7 years ago.
I'm trying to learn Spring MVC and Hibernate. When I try to run tests I have "Exception in thread "main" java.lang.NullPointerException".
public interface VacancyDAO
package pro.asfert.jobparser.dao;
public interface VacancyDAO {
void LoadDataBase(String query);
void FindVacancy(String queries);}
public class VacancyDAOImpl
package pro.asfert.jobparser.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class VacancyDAOImpl implements VacancyDAO {
#Autowired
private SessionFactory sessionFactory;
public void LoadDataBase(String query) {
sessionFactory.getCurrentSession().createQuery(query);
}
public void FindVacancy(String queries) {
if (queries.contains("По вашему запросу: ")) {
System.out.print(queries);
} else {
sessionFactory.getCurrentSession().createQuery(queries);
}
}
}
public interface VacancyService
package pro.asfert.jobparser.service;
public interface VacancyService {
void LoadDataBase();
void FindVacancy(String queries);
}
**public class VacancyServiceImpl**
package pro.asfert.jobparser.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pro.asfert.jobparser.dao.VacancyDAO;
import pro.asfert.jobparser.domain.Parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
#Service
public class VacancyServiceImpl implements VacancyService {
#Autowired
private VacancyDAO VacancyDAO;
public static void main(String[] args) {
VacancyServiceImpl vacancyService = new VacancyServiceImpl();
vacancyService.FindVacancy("test");
}
/* deleted */
#Transactional
public void LoadDataBase() {
VacancyDAO.LoadDataBase(query);
}
#Transactional
public void FindVacancy(String queries) {
VacancyDAO.FindVacancy(sqlQuery);
}
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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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/cache
http://www.springframework.org/schema/cache/spring-cache.xsd ">
<context:annotation-config />
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="ENVIRONMENT"/>
<context:component-scan base-package="pro.asfert.jobparser.dao"/>
<context:component-scan base-package="pro.asfert.jobparser.service"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory">
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value = "${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.databaseurl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id = "sessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref = "dataSource"/>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
</props>
</property>
</bean>
</beans>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class = "pro.asfert.jobparser.domain.Vacancy"></mapping>
</session-factory>
</hibernate-configuration>
Vacancy
package pro.asfert.jobparser.domain;
import javax.persistence.*;
#Entity
#Table(name = "Vacancies")
public class Vacancy {
public Vacancy() {
}
#Id
#Column(name = "id")
#GeneratedValue
private Integer id;
#Column (name = "vacancy")
private String vacancy;
#Column (name = "salary")
private String salary;
#Column (name = "experience")
private String experience;
#Column (name = "education")
private String education;
#Column (name = "employer")
private String employer;
#Column (name = "details")
private String details;
#Column (name = "hr")
private String hr;
#Column (name = "url")
private String url;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getVacancy() {
return vacancy;
}
public void setVacancy(String vacancy) {
this.vacancy = vacancy;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getEmployer() {
return employer;
}
public void setEmployer(String employer) {
this.employer = employer;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getHr() {
return hr;
}
public void setHr(String hr) {
this.hr = hr;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
You're creating the service with new here:
public static void main(String[] args) {
VacancyServiceImpl vacancyService = new VacancyServiceImpl();
vacancyService.FindVacancy("test");
}
That way Spring is not involved and does not know anything about this object.
How to fix it:
register your dao and service as spring beans.
initialize the context and get the service from the context and call your method.
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
VacancyServiceImpl serv = ctx.getBean(VacancyServiceImpl.class);
serv.FindVacancy("test");

No Session found for current thread] when invoke Service method

I try invoke my method which return admin lists, but when I invoke this method i get the error no session found.
roo-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: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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:XE" />
<property name="username" value="HR" />
<property name="password" value="asdfghj" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="pl.piotr.ibank.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
<prop key="hibernate.show_sql">
true
</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="myAuthenticationSuccessHandler" class="pl.piotr.ibank.security.MyAuthenticationSuccessHandler" />
</beans>
servlet-context:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<context:component-scan base-package="pl.piotr.ibank" />
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:beans>
UserServiceImpl:
package pl.piotr.ibank.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.piotr.ibank.daointerface.UserDao;
import pl.piotr.ibank.model.User;
import pl.piotr.ibank.serviceinterface.UserService;
#Service
#Transactional
public class UserServiceImpl implements UserService {
#Autowired
UserDao userDao;
#Override
public void createUser(User user) {
userDao.createUser(user);
}
#Override
public void updateUser(User user) {
userDao.updateUser(user);
}
#Override
public void deleteUser(int id) {
userDao.deleteUser(id);
}
#Override
public User getUser(int id) {
return userDao.getUser(id);
}
#SuppressWarnings("rawtypes")
#Override
public List getAdminList() {
return userDao.getAdminList();
}
#Override
public User findByUsername(String username) {
return userDao.findByUsername(username);
}
}
UserService interface:
package pl.piotr.ibank.serviceinterface;
import java.util.List;
import pl.piotr.ibank.model.User;
public interface UserService {
void createUser(User user);
void updateUser(User user);
void deleteUser(int id);
User getUser(int id);
#SuppressWarnings("rawtypes")
List getAdminList();
User findByUsername(String username);
}
UserDaoImpl
package pl.piotr.ibank.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import pl.piotr.ibank.daointerface.UserDao;
import pl.piotr.ibank.model.User;
#Repository
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void createUser(User user) {
getCurrentSession().save(user);
}
#Override
public void updateUser(User user) {
getCurrentSession().update(user);
}
#Override
public void deleteUser(int id) {
User user = getUser(id);
if (user != null) {
getCurrentSession().delete(user);
}
}
#Override
public User getUser(int id) {
User user = (User) getCurrentSession().get(User.class, id);
return user;
}
#SuppressWarnings("rawtypes")
#Override
public List getAdminList() {
return getCurrentSession()
.createQuery(
"from User u, UserRole ur where u.id = ur.user.id and ur.user = 'ROLE_ADMIN'")
.list();
}
#SuppressWarnings("unchecked")
#Override
public User findByUsername(String username) {
List<User> users = new ArrayList<User>();
System.out.println(username);
try {
users = getCurrentSession()
.createQuery("from User where username=:username")
.setParameter("username", username).list();
System.out.println("Liczba " + users.size());
} catch (Exception e) {
System.out.println(e.getMessage());
}
if (users.size() > 0) {
return users.get(0);
} else {
return null;
}
}
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}
UserDao interface:
package pl.piotr.ibank.daointerface;
import java.util.List;
import pl.piotr.ibank.model.User;
public interface UserDao {
void createUser(User user);
void updateUser(User user);
void deleteUser(int id);
User getUser(int it);
#SuppressWarnings("rawtypes")
List getAdminList();
User findByUsername(String username);
}
Controller which invoke getAdminList:
package pl.piotr.ibank.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import pl.piotr.ibank.model.User;
import pl.piotr.ibank.serviceinterface.UserService;
#Controller
public class AdminController {
#Autowired
private UserService userService;
#SuppressWarnings("unchecked")
#RequestMapping(value = "/admin/adminlist", method = RequestMethod.GET)
public ModelAndView goAdminList() {
ModelAndView mav = new ModelAndView("admin/adminlist");
List<User> admins = userService.getAdminList();
mav.addObject("admins", admins);
return mav;
}
}
Login method work good, loadbyusername, but when i invoke method service.getAdminList() i have this error:
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/ibank] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread] with root cause
org.hibernate.HibernateException: No Session found for current thread
I find that in your code you auto wire 'Sessionfactory' in your DAO implement, which means that you needs to handle session manually, including open session and close session when necessary. Since you are using Spring and hibernate, I suggest to use Template like HiberateTemplate, which Spring will take care of session for you. Every time you want to use session, just call 'getCurrentSession()', like what you are doing in you code.
Try to make a abstract DAO class that extends HibernateDaoSupport, like
public abstract class BasicDAO extends HibernateDaoSupport{
......
}
For your DAO implement, extends this class, and you code would work fine.

Spring service layer object comes null

Hi I am learning Spring and has stuck to a problem.
I have a structure something like the following:
package com.edfx.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "CUSTOMER")
public class Customer {
private long customer_id;
private String name;
private String address;
private Date created_date;
#Id
#Column(name = "CUSTOMER_ID")
public long getCustomer_id() {
return customer_id;
}
public void setCustomer_id(long customer_id) {
this.customer_id = customer_id;
}
#Column(name = "NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "ADDRESS")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "CREATED_DATE")
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}
#Override
public String toString(){
StringBuffer strBuffer = new StringBuffer();
strBuffer.append("customer_id:").append(getCustomer_id());
strBuffer.append(", name : ").append(getName());
strBuffer.append(", address: ").append(getAddress());
strBuffer.append(", created_date: ").append(getCreated_date());
return strBuffer.toString();
}
}
The Managed Bean is:
package com.edfx.managedbean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import org.springframework.dao.DataAccessException;
import com.edfx.customer.service.ICustomerService;
import com.edfx.model.Customer;
#ManagedBean(name = "customerMB")
#SessionScoped
public class CustomerManagedBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8839370045113377019L;
private static final String SUCCESS = "success";
private static final String ERROR = "error";
// Spring Customer Service Injection
ICustomerService customerService;
public ICustomerService getCustomerService() {
System.out.println("customerService -- >"+customerService);
return customerService;
}
public void setCustomerService(ICustomerService customerService) {
this.customerService = customerService;
}
List<Customer> userList;
private long customer_id;
private String name;
private String address;
private Date created_date;
public String addUser(){
System.out.println("Managed Bean Add User..");
try {
Customer customer = new Customer();
System.out.println("ID :: "+getCustomer_id());
customer.setCustomer_id(getCustomer_id());
System.out.println("Name :: "+getName());
customer.setName(getName());
System.out.println("Address :: "+getAddress());
customer.setAddress(getAddress());
System.out.println("Created Date :: "+new Date());
customer.setCreated_date(new Date());
//Service Provider
getCustomerService().addUser(customer);
return SUCCESS;
} catch (DataAccessException e) {
System.err.println("Error Occured :: "+e.getMessage());
}
return ERROR;
}
public void reset(){
this.setCustomer_id(0);
this.setName("");
this.setAddress("");
this.setCreated_date(null);
}
public List<Customer> getUserList(){
userList = new ArrayList<Customer>();
System.out.println("BEAN :: "+getCustomerService().getUsers());
userList.addAll(getCustomerService().getUsers());
return userList;
}
public void setUserList(List<Customer> userList) {
this.userList = userList;
}
public long getCustomer_id() {
return customer_id;
}
public void setCustomer_id(long customer_id) {
this.customer_id = customer_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}
}
The applicationContextFile is:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:component-scan base-package="com.edfx.managedbean"/>
<context:annotation-config/>
<!-- Bean Declaration -->
<bean id="Customer" class="com.edfx.model.Customer"/>
<!-- Customer Service Declaration -->
<bean id="customerService" class="com.edfx.customer.service.CustomerService" scope="prototype">
<property name="customerDAO" ref="CustomerDAO"/>
</bean>
<!-- Customer DAO Declaration -->
<bean id="CustomerDAO" class="com.edfx.customer.dao.CustomerDAO">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
<!-- Data Source Declaration -->
<bean id="DataSource" 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/mydatabase"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
<property name="maxPoolSize" value="10"/>
<property name="maxStatements" value="0"/>
<property name="minPoolSize" value="5"/>
</bean>
<!-- Session Factory Declaration -->
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource"/>
<property name="annotatedClasses">
<list>
<value>com.edfx.model.Customer</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>
<!-- Enable the configuration of transactional behaviour based on annotation -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Transaction Manager is defined -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="runMeJob"/>
</list>
</property>
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
<!-- Spring Configuration Manager -->
<bean id="runMeTask" class="com.edfx.customer.schedular.RunMeTask"/>
<!-- Spring Quartz -->
<bean name="runMeJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.edfx.customer.schedular.RunMeJob"/>
<property name="jobDataAsMap">
<map>
<entry key="runMeTask" value-ref="runMeTask"/>
</map>
</property>
</bean>
<!-- Simple Trigger every 5 secs
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="runMeJob"/>
<property name="repeatInterval" value="5000"/>
<property name="stratDelay" value="1000"/>
</bean> -->
<!-- CronTrigger runs every 5 secs-->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="runMeJob"/>
<property name="misfireInstructionName" value="MISFIRE_INSTRUCTION_FIRE_ONCE_NOW" />
<property name="cronExpression" value="0 30 19 * * ?"/>
</bean>
Here I have set a schedular. The scheduler works absolutely fine as it fires properly at the specific time.
Here is the Job details that is scheduled to run:
package com.edfx.customer.schedular;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.naming.directory.Attributes;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.context.ContextLoader;
import com.edfx.customer.ldap.mngr.LDAPManager;
import com.edfx.customer.service.CustomerService;
import com.edfx.customer.service.ICustomerLdapSyncService;
import com.edfx.customer.service.ICustomerService;
import com.edfx.managedbean.CustomerManagedBean;
import com.edfx.model.Customer;
public class RunMeJob extends QuartzJobBean{
private RunMeTask runMeTask;
#Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
ApplicationContext applicationContext = null;
try {
applicationContext = (ApplicationContext)context.getScheduler().getContext().get("applicationContext");
} catch (Exception e) {
System.err.println("Synchronization Error :: "+e.getMessage());
}
if(applicationContext == null)
applicationContext = ContextLoader.getCurrentWebApplicationContext();
System.out.println("=============== SCHEDULAR SERVICE ON =================");
System.out.println("MAP DETAILS == >"+new LDAPManager().getUserDetails());
Map<String, String> userDetailsMap = new LDAPManager().getUserDetails();
CustomerManagedBean customerManagedBean = new CustomerManagedBean();
int i=0;
for(Map.Entry<String, String> entry : userDetailsMap.entrySet()){
i++;
String key = entry.getKey();
String value = entry.getValue();
System.out.println("Key -->"+key+" :: Value-->"+value);
customerManagedBean.setCustomer_id(i);
customerManagedBean.setName(key);
customerManagedBean.setAddress(value);
customerManagedBean.setCreated_date(new Date());
}
customerManagedBean.addUser();
runMeTask.printMe();
System.out.println("=============== SCHEDULAR SERVICE OFF ================");
}
public void setRunMeTask(RunMeTask runMeTask) {
this.runMeTask = runMeTask;
}
}
Here, the method addUser() invokes properly. But while executing getCustomerService().addUser(customer); it throws NullPointerException as it gets customerService object null, which has been injected in the CustomerManagedBean class. mentioned in applicationContext.xml.
What could be the possible reason for this?
Please Help!
First problem I found is that, in your executeInternal method you are not using customerManagedBean from your Spring application context. Instead of that, you are creating one like bellow:
CustomerManagedBean customerManagedBean = new CustomerManagedBean();
And when you are creating your own bean, its your responsibility to prepare it before use (injection or initialization), because you are not using it from any context made and managed by any framework (Spring or something else). You could avoid these problems by simply getting the bean from Spring's ApplicationContext, by replacing the above line with the line bellow:
CustomerManagedBean customerManagedBean = (CustomerManagedBean)applicationContext.getBean("beanName")
Second thing,
Are you using JSF with Spring?
If your answer is no, then why you are using JSF annotations (#ManagedBean and #SessionScoped). As these annotations are not recognizable to Spring. Spring actually doesn't instantiate it in its context. Although you putted,
<context:component-scan base-package="com.edfx.managedbean"/>
in your applicationContext.xml.
If your answer is yes, then you should follow, the following tutorials properly to configure successfully:
jsf 2.0 spring integration example
jsf 2.0 spring hibernate integration example

No Session found for current thread (HIBERNATE)

OK JAVA guru ))
I really new to spring and I got into this trouble with "No session found the current thread" when I refer to the following page JSP security after login. Up to this point everything is working.
I need your help guys!!!!!
Here is my controller for that page:
package employee.controller;
import employee.service.AdminService;
import employee.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource;
/**
* #author serge
*
* Handles and retrieves the common or admin page depending on the URI template.
* A user must be log-in first he can access these pages. Only the admin can see
* the adminpage, however.
*/
#Controller
#RequestMapping("/main")
public class MainController {
protected static Logger logger = Logger.getLogger("controller");
#Resource(name = "adminService")
private AdminService adminService;
#Resource(name = "userService")
private UserService userService;
/**
* Handles and retrieves a /WEB-INF/jsp/employee-page.jsp
*
* containing all employee
*
* #return the name of the JSP page
*/
#Secured("ROLE_USER")
#RequestMapping(value = "/employee-list",method = RequestMethod.GET)
public String getEmployeeListPage(Model model) {
logger.debug("Received request to show all employee page");
// Retrieve all employee and attach to model
model.addAttribute("all-employee", userService.findAllEmployee());
return "employee-page";
}
/**
* Handles and retrieves /WEB-INF/jsp/admin-page.jsp that only admins can see
*
* #return the name of the JSP page
*/
#Secured("ROLE_ADMIN")
#RequestMapping(value = "/admin", method = RequestMethod.GET)
public String getAdminPage() {
logger.debug("Received request to show admin page");
return "admin-page";
}
}
This is user service that had been called from controller:
package employee.service.impl;
import employee.DAO.EmployeeInfoDAO;
import employee.model.EmployeeInfo;
import employee.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* #author serge
*
* Reader level
*
* Service to Retrieve info about Employees
*/
#Service("userService")
#Transactional
public class UserServiceImpl implements UserService {
protected static Logger logger = Logger.getLogger("service");
private EmployeeInfoDAO emplInfoDAO;
#Autowired
public void setEmployeeDao(EmployeeInfoDAO emplInfoDAO) {
this.emplInfoDAO = emplInfoDAO;
}
/**
* Retrieving Employee Information by id
*
* #return EmployeeInfo object
*/
#Override
#Transactional
#Secured("ROLE_USER")
public EmployeeInfo findEmployeeByID(Integer id) {
logger.debug("Retrieving Employee with id= " + id);
EmployeeInfo employeeInfo = new EmployeeInfo();
employeeInfo.setId(id);
emplInfoDAO.find(employeeInfo);
return employeeInfo;
}
/**
* Retrieving all Employees
*
* #return List of EmployeeInfo object
*/
#Override
#Secured("ROLE_USER")
#Transactional(readOnly = true)
public List<EmployeeInfo> findAllEmployee() {
logger.debug("Retrieving all Employee");
return emplInfoDAO.findAll();
}
/**
* Retrieving Employees by last name
*
* #return List of EmployeeInfo object
*/
#Override
#Secured("ROLE_USER")
#Transactional(readOnly = true)
public List<EmployeeInfo> findAllByLastName(String lastName, Object paramValue) {
lastName = "lastName";
logger.debug("Retrieving Employee by last name: " + paramValue);
return emplInfoDAO.findAllByParam(lastName, paramValue);
}
/**
* Retrieving Employees by first name
*
* #return List of EmployeeInfo object
*/
#Override
#Secured("ROLE_USER")
#Transactional(readOnly = true)
public List<EmployeeInfo> findAllByFirstName(String firstName, Object paramValue) {
firstName = "firstName";
logger.debug("Retrieving Employee by first name: " + paramValue);
return emplInfoDAO.findAllByParam(firstName, paramValue);
}
}
And this is custom DAO support, not sure if this is right way to do that.... :
package employee.DAO.impl;
import employee.DAO.DAO;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
public class CustomHibernateDaoSupport<T> implements DAO<T> {
//was extending HibernateDaoSupport
private Class<T> clazz;
private SessionFactory sessionFactory;
public CustomHibernateDaoSupport(Class<T> clazz) {
this.clazz = clazz;
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
#Override
#Transactional
public void save(T entity) {
getCurrentSession().save(entity);
}
#Override
#Transactional
public void update(T entity) {
getCurrentSession().update(entity);
}
#Override
#Transactional
public void delete(Serializable key) {
Object entity = getCurrentSession().get(clazz, key);
if (entity != null) {
getCurrentSession().delete(entity);
}
}
#Override
#Transactional
public T find(Serializable key) {
return (T) getCurrentSession().get(clazz, key);
}
#Override
#Transactional
public List<T> findAll() {
return getCurrentSession().createCriteria(clazz).list();
}
#Override
#Transactional
public List<T> findAllByParam(final String paramName, final Object paramValue) {
return getCurrentSession().createCriteria(clazz)
.add(Restrictions.eq(paramName, paramValue))
.list();
}
}
And of course configuration:
<?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:mvc="http://www.springframework.org/schema/mvc"
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-3.1.xsd">
<!-- Activates annotations -->
<context:annotation-config />
<mvc:annotation-driven/>
<!-- Scans for annotated components in base-package-->
<context:component-scan base-package="employee" />
<bean class="employee.service.impl.AdminServiceImpl"/>
<bean class="employee.service.impl.UserServiceImpl"/>
<!-- Shared Hibernate SessionFactory in a Spring application context. -->
<bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name = "sessionFactory" ref = "sessionFactory" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>employee.model.UserInfo</value>
<value>employee.model.EmployeeInfo</value>
<value>employee.model.EmployeeDiv</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!-- for database, imports the properties from database.properties -->
<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 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:database.properties"/>
</bean>
</beans>
after a successful login, I called /employee-list and got this instead of the page:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
...
org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:941)
employee.DAO.impl.CustomHibernateDaoSupport.getCurrentSession(CustomHibernateDaoSupport.java:31)
employee.DAO.impl.CustomHibernateDaoSupport.findAll(CustomHibernateDaoSupport.java:64)
...
Please help me understand where is my mistake, maybe I made a wrong configuration?
If you have dispatch-servlet.xml, add the
<tx:annotation-driven />
Or there is an alternative:
Please see this:
this blog

nullpointer exception in getcurrentsession

I am trying to integrate Hibernate 4.1 with Spring 3.1.3.
//configuration file (beans.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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd ">
<bean id="employeeDAObean" class="com.Hib_Spring.EmployeeDAO">
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceBean"></property>
<property name="annotatedClasses" value="com.Hib_Spring.Employee"> </property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/newdatabase"/>
<property name="username" value="postgres"/>
<property name="password" value="P#ssword"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
</beans>
This is my model class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee_new")
public class Employee {
#Id
#Column(name="ID")
private int id;
#Column (name="firstname")
private String first_name;
#Column(name="lastname")
private String last_name;
public Employee() {}
public Employee(int id,String fname, String lname) {
this.first_name = fname;
this.last_name = lname;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return first_name;
}
public void setFirstName( String first_name ) {
this.first_name = first_name;
}
public String getLastName() {
return last_name;
}
public void setLastName( String last_name ) {
this.last_name = last_name;
}
}
Following is my DAO class
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class EmployeeDAO {
#Autowired
SessionFactory sessionFactory;
public void createEmployee(int id, String fname, String lname)
{
Employee emp1 = new Employee(id,fname,lname);
sessionFactory.getCurrentSession().save(emp1);
}
public List getAllEmployees(){
return sessionFactory.getCurrentSession().createQuery("from employee_new").list();
}
}
My table has three columns ID, firstname,lastname
This is the main class(Client.java)
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String arg[]){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
EmployeeDAO employeedao=context.getBean("employeeDAObean",EmployeeDAO.class);
System.out.println("Entering data in the database");
employeedao.createEmployee(101, "aaa", "bbb");
employeedao.createEmployee(102, "ccc", "ddd");
System.out.println("Reading the data");
List employeelist= employeedao.getAllEmployees();
for(int i=0;i<employeelist.size();i++){
Employee e = (Employee) employeelist.get(i);
System.out.println("Emp No "+e.getId());
System.out.println("FirstName "+e.getFirstName());
System.out.println("LastName "+e.getLastName());
}
}
}
Now my problem is that whenever I try to execute client.java I am getting a nullpointer exception in
sessionFactory.getCurrentSession().save(emp1);
of the EmployeeDAO class.
Right now my table is empty and I am trying to add a record in it. I dont what is the exact mistake I have done. I am sure there should be a silly one. Could someone throw some light on it. Thanks for the help!
You have tx:annotation-driven but I do not see any transaction annotations. Try putting the annotation on the createEmployee method of the dao and that will get it going.

Resources