javax.persistence.TransactionRequiredException - spring

I am getting the below error, I have gone through all of the similar issues, but don't able to figure out where I am going wrong.
Here is the error:
Exception in thread "main" javax.persistence.TransactionRequiredException: No transactional EntityManager available
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:275)
at com.sun.proxy.$Proxy19.persist(Unknown Source)
at com.project.vibhas.dao.hibernate.GenericDaoJpa.save(GenericDaoJpa.java:45)
at com.project.vibhas.service.impl.PersonServiceImpl.save(PersonServiceImpl.java:22)
at com.project.vibhas.domain.App.main(App.java:25)
Here are my code:
package com.project.vibhas.dao.hibernate;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
import com.project.vibhas.dao.GenericDao;
import com.project.vibhas.domain.DomainObject;
public class GenericDaoJpa<T extends DomainObject> implements GenericDao<T> {
private Class<T> type;
protected EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public GenericDaoJpa(Class<T> type) {
super();
this.type = type;
}
#Transactional
public void save(T object) {
System.out.println("inside generic dao");
entityManager.persist(object);
}
public void delete(T object) {
entityManager.remove(object);
}
}
My Dao class:
#Repository("personDao")
public class PersonDaoJpa extends GenericDaoJpa<Person> implements PersonDao {
public PersonDaoJpa() {
super(Person.class);
}
public Person authenticatePerson(String username, String password)
throws DataAccessException, AuthenticationException {
List<Person> results = null;
Query query = entityManager
.createQuery("from Person as p where p.username = :username and p.password = :password");
query.setParameter("username", username);
query.setParameter("password", password);
results = query.getResultList();
if (results == null || results.size() <= 0) {
throw new AuthenticationException("No users found");
} else {
return results.get(0);
}
}
public Person getPersonByUsername(String username)
throws DataAccessException, EntityNotFoundException {
List<Person> results = null;
Query query = entityManager
.createQuery("from Person as p where p.username = :username");
query.setParameter("username", username);
results = query.getResultList();
if (results == null || results.size() <= 0) {
throw new EntityNotFoundException(username + " not found");
} else {
return results.get(0);
}
}
}
My sercice Class:
package com.project.vibhas.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.project.vibhas.dao.PersonDao;
import com.project.vibhas.domain.Person;
import com.project.vibhas.service.PersonService;
#Service("personService")
public class PersonServiceImpl implements PersonService{
#Autowired
PersonDao personDao;
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public void save(Person person) {
System.out.println("Inside service");
//personDao.get(1L);
personDao.save(person);
}
}
My Test Class:
package com.project.vibhas.domain;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.project.vibhas.service.PersonService;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext appContext = new ClassPathXmlApplicationContext(
"classpath*:META-INF/spring/spring-jpa.xml");
PersonService personService = (PersonService) appContext.getBean("personService");
Person person = new Person();
person.setId(1L);
personService.save(person);
System.out.println("Done");
}
}
Spring-Jpa.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<!-- The rest of the config is covered below -->
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.project" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="org.postgresql.Driver"
p:url="jdbc:postgresql://localhost:5433/mypostgresdb"
p:username="postgres"
p:password="root" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
</beans>
Persistence.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"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="galleryPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<!--
value='create' to build a new database on each run;
value='update' to modify an existing database;
value='create-drop' to create and drop tables on each run;
value='validate' makes no changes to the database
-->
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>

Related

spring aop logging advice is not getting called

I am writing simple aspect with simple logging advice which will be called upon setter of class.
Below is code Snippet
AopMain.java
package com.example.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.example.test.model.Triangle;
import com.example.test.service.ShapeService;
public class AopMain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//ShapeService shapeService = context.getBean("shapeService", ShapeService.class);
//shapeService.getTriangle().setName("triangle");
Triangle triangle = new Triangle();
triangle.setName("triangle class");
System.out.println(triangle.getName());
}
}
Triangle.java
package com.example.test.model;
public class Triangle {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
System.out.println(name);
}
}
LoggingAspect.java
package com.example.test.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.example.test.model.Triangle;
#Component
#Aspect
public class LoggingAspect {
#Before("execution(public * *(..))")
public void LoggingAdvice(JoinPoint jPoint) {
System.out.println("Advice run. Get method is called " + jPoint.getTarget());
Triangle triangle = (Triangle) jPoint.getTarget();
}
#Before("args(name)")
public void test(String name) {
System.out.println("logging advice args " + name);
}
}
Output
triangle class
triangle class
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: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/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 ">
<!-- <bean id="triangle" class="com.example.test.model.Triangle">
<property name="name" value="Triangle Name"></property>
</bean> -->
<bean id="circle" class="com.example.test.model.Circle">
<property name="name" value="Circle Name"></property>
</bean>
<bean id="shapeService"
class="com.example.test.service.ShapeService" autowire="byType" />
<aop:aspectj-autoproxy />
<context:component-scan
base-package="com.example.test" />
</beans>
spring is working properly.
I do not understand why aspect is not gettting called.
please help me to understand this issue.

Spring service injection with #Autowired results NullPointerException

I am trying to inject a service in GeofenceMonitoring class using
#Autowired
private IDeviceService deviceService;
but I am getting a NullPointerException
This is the interface of the service and below it's implementation :
IDeviceService
package com.sifast.gpstracking.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.sifast.gpstracking.model.Device;
import com.sifast.gpstracking.service.util.IGenericService;
#Transactional
public interface IDeviceService extends IGenericService<Device, Integer> {
Device findDeviceByUniqueId(String uniqueId);
List<Device> findAllDevice();
}
DeviceService
package com.sifast.gpstracking.service.impl;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sifast.gpstracking.dao.impl.DeviceDao;
import com.sifast.gpstracking.model.Device;
import com.sifast.gpstracking.service.IDeviceService;
import com.sifast.gpstracking.service.util.GenericService;
#Service("deviceService")
public class DeviceService extends GenericService<Device, Integer> implements IDeviceService, Serializable {
private static final long serialVersionUID = 1L;
#Autowired
private DeviceDao deviceDao;
#Override
public Device findDeviceByUniqueId(String uniqueId) {
Query query = deviceDao.getSession().getNamedQuery("findDeviceByUniqueId").setString("uniqueId", uniqueId);
return deviceDao.findOne(query);
}
#Override
public List<Device> findAllDevice() {
return deviceDao.findAll(Device.class);
}
}
And here when I try to inject the service :
GeofenceMonitoring
package com.sifast.gpstracking.webServiceRest;
import java.util.ArrayList;
import java.util.List;
import org.primefaces.model.map.LatLng;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import com.sifast.gpastracking.monitoring.IMonitor;
import com.sifast.gpstracking.model.Device;
import com.sifast.gpstracking.model.Geofence;
import com.sifast.gpstracking.model.GeofenceDevice;
import com.sifast.gpstracking.model.Point;
import com.sifast.gpstracking.push.DevicePositionData;
import com.sifast.gpstracking.service.IDeviceService;
import com.sifast.gpstracking.service.util.IntersectionGeofence;
#ComponentScan("com.sifast.gpstracking")
public class GeofenceMonitor implements IMonitor {
ArrayList<Geofence> geofences = new ArrayList<Geofence>();
GeofenceDevice geofenceDevice;
Boolean geofenced=false;
public static final Logger logger = LoggerFactory.getLogger(GeofenceMonitor.class);
#Autowired
private IDeviceService serviceDevice;
public GeofenceMonitor() {
}
#Override
public void updateMonitor(DevicePositionData devicePositionData) {
//logger.debug("DEVICE ID = " + devicePositionData.getUniqueId());
Device device = serviceDevice.findDeviceByUniqueId(devicePositionData.getUniqueId());
LatLng currentPosition = new LatLng(devicePositionData.getLatitude(), devicePositionData.getLongitude());
for (GeofenceDevice geofenceDevice : device.getListGeofenceDevice()) {
List<LatLng> listPoint = convertListPointToListLatLng(geofenceDevice.getGeofence().getListPoint());
logger.debug("SIZE =====> "+listPoint.size());
if (IntersectionGeofence.isPointInsidePolygon(currentPosition, listPoint))
{
geofenced = true;
logger.debug("Le device " + devicePositionData.getDeviceName() + " a dépassé la zone limitée");
break;
}
}
}
private List<LatLng> convertListPointToListLatLng(List<Point> listPoint)
{
List<LatLng> listLatLng = new ArrayList<LatLng>();
for (Point point : listPoint){
listLatLng.add(new LatLng(point.getLatitude(),point.getLongitude()));
}
return listLatLng;
}
}
And finally 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:aop="http://www.springframework.org/schema/aop"
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-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<!-- Activates scanning of annotations -->
<context:component-scan base-package="com.sifast.gpstracking" />
<context:annotation-config/>
<context:spring-configured/>
<!-- Database Configuration -->
<import resource="/database/dataSource.xml" />
<import resource="/database/hibernate.xml" />
<!-- Transaction Manager is defined -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager" />
<mvc:annotation-driven></mvc:annotation-driven>
<!-- Pour avoir accès au resources comme les fichiers /js et /css lorsqu'on utilise un mapping / avec le servletDispatcher dans le web.xml -->
<mvc:resources mapping="/css/**" location="/resources/css/" />
<mvc:resources mapping="/images/**" location="/resources/images/" />
<!-- Init DataBase -->
<bean id="dbInit"
class="org.springframework.jdbc.datasource.init.ResourceDatabasePopulator">
<property name="scripts">
<list>
<value>classpath:sql/1.0.0/CreateData.sql</value>
</list>
</property>
<property name="continueOnError" value="true" />
</bean>
<bean id="startupScripts"
class="org.springframework.jdbc.datasource.init.DataSourceInitializer">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="databasePopulator">
<ref bean="dbInit" />
</property>
</bean>
</beans>
It's because that IDeviceService is an interface. Spring won't know which instance you want to autowire, since the default way to autowire is byType, if I'm not wrong.
Try this
#Autowired
#Qualifier("deviceService")
private IDeviceService deviceService;
try double stars first
<context:component-scan base-package="com.sifast.gpstracking.**" />
An simple example to get bean via applicationContext.getBean()
http://www.mkyong.com/spring/quick-start-maven-spring-example/
And you want to get it in web environment, you can inject it.
How to inject ApplicationContext itself
Is your GeofenceMonitor bean registered in the application context ? From your code snippets its missing streotype annotations (#Component / #Service etc) So it wont be auto detected and any specified dependencies wont be injected. Change #ComponentScan("com.sifast.gpstracking")
public class GeofenceMonitor implements IMonitor to #Component public class GeofenceMonitor implements IMonitor
the problem was that I am creating a new instance of GeofenceMonitor with new GeofenceMonitor() in a service class that's meant to handle the web service invokation.
So I modified it to #Scope("singleton") and added #PostConstruct private void init(). Below is my code:
PositionNotification (web service class)
#Service("positionNotification")
#Path("/positionNotification")
#Scope("singleton")
public class PositionNotification implements Serializable, IMonitorable {
private static final long serialVersionUID = 1L;
#Autowired
private GeofenceMonitor geofence;
private static ArrayList<IMonitor> monitors;
/*static {
monitors = new ArrayList<IMonitor>();
monitors.add(new SpeedMonitor());
monitors.add(geofence);
}*/
#Autowired
private IDeviceService deviceService;
#Autowired
private IPositionService positionService;
private final static String CHANNEL = "/notify";
public static final Logger logger = LoggerFactory.getLogger(PositionNotification.class);
private static final int STATUS_OK = 200;
#PostConstruct
private void init(){
monitors = new ArrayList<IMonitor>();
monitors.add(new SpeedMonitor());
monitors.add(geofence);
}
#POST
#Path("/getGeoLocFromDevice")
public Response test(#FormParam("LATITUDE") String latitude, #FormParam("LONGITUDE") String longitude, #FormParam("DEVICE_ID") String uniqueId,
#FormParam("SPEED") String speed, #FormParam("Horodateur") String date) {
logger.debug("X long: " + latitude + " __ Y lat: " + longitude + " uniqueId " + uniqueId + " " + date);
Device device = deviceService.findDeviceByUniqueId(uniqueId);
if (device != null) {
if (speed == null) {
speed = "0";
}
String address = AddressResolver.AddressReseolve(latitude, longitude);
DevicePositionData devicePositionData = new DevicePositionData();
devicePositionData.setLatitude(Double.valueOf(latitude));
devicePositionData.setLongitude(Double.valueOf(longitude));
devicePositionData.setUniqueId(uniqueId);
devicePositionData.setAddress(address);
devicePositionData.setDeviceName(device.getName());
devicePositionData.setSpeed(Double.parseDouble(speed));
devicePositionData.setIcon(device.getType().getIconActive());
Position position = new Position();
position.setAddress(address);
position.setLatitude(Double.valueOf(latitude));
position.setLongitude(Double.valueOf(longitude));
if (date != null) {
try {
position.setDatePosition(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse(date));
devicePositionData.setDatePosition(date);
device.setLastUpdate(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
} else {
position.setDatePosition(new Date());
devicePositionData.setDatePosition(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date()));
device.setLastUpdate(new Date());
}
position.setSpeed(Double.parseDouble(speed));
position.setDevice(device);
positionService.saveOrUpdateService(position);
deviceService.saveOrUpdateService(device);
if (EventBusFactory.getDefault() != null) {
EventBus eventBus = EventBusFactory.getDefault().eventBus();
eventBus.publish(CHANNEL, devicePositionData);
}
notifyMonitors(devicePositionData);
}
return Response.status(STATUS_OK).build();
}
#Override
public void notifyMonitors(DevicePositionData devicePositionData) {
for (IMonitor monitor : monitors) {
monitor.updateMonitor(devicePositionData);
}
}
#Override
public void addMonitor(IMonitor monitor) {
monitors.add(monitor);
}
#Override
public void deleteMonitor(IMonitor monitor) {
monitors.remove(monitor);
}
#Override
public void clearMonitors() {
monitors.clear();
}
}

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.

Received :org.springframework.transaction.CannotCreateTransactionException

I am making a JPA application in eclipse.I have designed the service layer with spring.I have
used "HibernatePersistence" as persistence provider.
Below is my persistence layer:
#MappedSuperclass
public class BaseEntity implements Serializable{
/**
*
*/
#Transient
private static final long serialVersionUID = -2265881632984808864L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID",nullable=false,updatable=false)
private Long id;
/**
* #return the id
*/
public Long getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
}
package com.edfx.jpapp.persist.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name = "Customer", schema = "customerdb")
public class Customer extends BaseEntity {
/**
*
*/
#Transient
private static final long serialVersionUID = 1443119926544372161L;
#Column(name = "CUSTOMER_NAME", nullable = false, length = 30)
private String customerName;
#Column(name = "CUSTOMER_ADDRESS", nullable = false, length = 25)
private String customerAddress;
/**
* #return the customerName
*/
public String getCustomerName() {
return customerName;
}
/**
* #param customerName
* the customerName to set
*/
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
/**
* #return the customerAddress
*/
public String getCustomerAddress() {
return customerAddress;
}
/**
* #param customerAddress
* the customerAddress to set
*/
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
/**
* #return the serialversionuid
*/
public static long getSerialversionuid() {
return serialVersionUID;
}
}
here is my DAO layer
package com.edfx.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.edfx.jpapp.dao.CustomerDAO;
import com.edfx.jpapp.persist.entity.Customer;
public class CustomerDAOImpl implements CustomerDAO {
#PersistenceContext(unitName="customerUnit")
private EntityManager entityManager;
/**
* #return the entityManager
*/
public EntityManager getEntityManager() {
return entityManager;
}
/**
* #param entityManager
* the entityManager to set
*/
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Override
public void insertCustomer(Customer customer) {
entityManager.persist(customer);
}
#Override
public List<Customer> getAllCustomer() {
return entityManager.createQuery("select c from customer c",
Customer.class).getResultList();
}
}
here is the service layer
package com.edfx.jpapp.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.dozer.Mapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.edfx.jpapp.dto.CustomerDTO;
import com.edfx.jpapp.persist.entity.Customer;
import com.edfx.jpapp.service.CustomerService;
import com.edfx.jpapp.service.base.BaseService;
#Transactional
public class CustomerServiceImpl extends BaseService implements CustomerService {
#Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
#Override
public void insertCustomer(CustomerDTO customerDTO) {
Customer customer = getBeanMapper().map(customerDTO, Customer.class);
getDaoProvider().getCustomerDAO().insertCustomer(customer);
}
#Transactional(readOnly = true)
#Override
public List<CustomerDTO> getAllCustomer() {
Mapper mapper = getBeanMapper();
ArrayList<CustomerDTO> customerDTOs = new ArrayList<CustomerDTO>();
List<Customer> customers = getDaoProvider().getCustomerDAO()
.getAllCustomer();
for (Customer customer : customers) {
CustomerDTO customerDTO = mapper.map(customer, CustomerDTO.class);
customerDTOs.add(customerDTO);
}
return customerDTOs;
}
}
I have placed my persistence.xml file under META-INF Folder: and it is as follows
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="customerUnit"
transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/jBossCustomerMysql</jta-data-source>
<class>com.edfx.jpapp.persist.entity.Customer</class>
<validation-mode>NONE</validation-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
I have used JTA DataSource and I have configured the JNDI in jboss standalone.xml file
as follows:
<datasource jta="true" jndi-name="java:/jBossCustomerMysql" pool-name="jBossCustomerMysql" enabled="true" use-ccm="false">
<connection-url>jdbc:mysql://localhost:3306/customerdb</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<driver>mysql</driver>
<security>
<user-name>root</user-name>
<password>root</password>
</security>
<validation>
<validate-on-match>false</validate-on-match>
<background-validation>false</background-validation>
</validation>
<statement>
<share-prepared-statements>false</share-prepared-statements>
</statement>
</datasource>
well when I ran the application my Tables got created in database.But when I try to insert a customer from xhtml page then I got the exception::
13:52:37,227 SEVERE [javax.faces.event] (http-localhost-127.0.0.1-8087-2) Received 'org.springframework.transaction.CannotCreateTransactionException' when invoking action listener '#{customerController.addCustomer}' for component 'j_idt9'
13:52:37,227 SEVERE [javax.faces.event] (http-localhost-127.0.0.1-8087-2) org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NullPointerException
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:427)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:329)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy22.insertCustomer(Unknown Source)
at com.edfx.jpapp.web.controller.CustomerController.addCustomer(CustomerController.java:56)
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.apache.el.parser.AstValue.invoke(AstValue.java:262)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:148)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:769)
Below is my spring 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="customerUnit" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="packagesToScan" value="com.edfx.jpapp.persist.entity" />
</bean>
</beans>
anther one is transactionConfig.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: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.1.xsd">
<bean id="transactionInterceptor" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributeSource">
<bean class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
can anyone give any solution to this??????
I have found the solution.I need to add the following piece of code to my persistence.xml file.
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>

java.lang.NullPointerException on #Inject Dao

I'm trying to Inject a DAO into #Service component, but I get this error :
Exception in thread "main" java.lang.NullPointerException at
it.cle.project.service.impl.TestEntityServiceImpl.getListTestEntity(TestEntityServiceImpl.java:24).
Fails to call the DAO which is null despite the annotation #Autowired
Below my code:
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- INIZIO IMPOSTAZIONI LEGATE ALLE ANNOTATIONS -->
<tx:annotation-driven/>
<context:property-placeholder location="classpath:hibernate.properties"/>
<context:component-scan base-package="it.cle.project.service.impl" />
<context:component-scan base-package="it.cle.project.dao.hbn" />
<context:component-scan base-package="it.cle.project.dao.hibernate" />
<!-- FINE IMPOSTAZIONI LEGATE ALLE ANNOTATIONS -->
<!-- INIZIO IMPOSTAZIONI LEGATE AD ALTRI FILE DI CONFIGURAZIONE -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:hibernate.properties"/>
</bean>
<!-- FINE IMPOSTAZIONI LEGATE AD ALTRI FILE DI CONFIGURAZIONE -->
<!-- INIZIO IMPOSTAZIONI LEGATE ALLA CONNESSIONE -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" />
<util:properties id="hibernateProperties">
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl_auto}</prop>
</util: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="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean "
p:dataSource-ref="dataSource" p:packagesToScan="it.cle.project.model"
p:hibernateProperties-ref="hibernateProperties" />
<!-- FINE IMPOSTAZIONI LEGATE ALLA CONNESSIONE -->
App.java
package it.cle.project;
import it.cle.project.model.TestEntity;
import it.cle.project.service.impl.TestEntityServiceImpl;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
System.out.println( "Hello World!" );
TestEntity testEntity = new TestEntity();
testEntity.setCampoUno("Campo Uno");
testEntity.setCampoDue("Campo Due");
testEntity.setEmail("email#test.it");
TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();
List<TestEntity> testEntitys = testEntityServiceImpl.getListTestEntity();
}
}
DAO Interface
package it.cle.project.dao;
import java.io.Serializable;
import java.util.List;
public interface Dao<T extends Object> {
void create(T t);
T get(Serializable id);
T load(Serializable id);
List<T> getAll();
void update(T t);
void delete(T t);
void deleteById(Serializable id);
void deleteAll();
long count();
boolean exists(Serializable id);
}
TestEntityDAO interface
package it.cle.project.dao;
import it.cle.project.model.TestEntity;
import java.util.List;
public interface TestEntityDao extends Dao<TestEntity> {
List<TestEntity> findByEmail(String email);
}
AbstractHbnDao Abstract class:
package it.cle.project.dao.hibernate;
import it.cle.project.dao.Dao;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;
#Service
public abstract class AbstractHbnDao<T extends Object> implements Dao<T> {
#Autowired
private SessionFactory sessionFactory;
private Class<T> domainClass;
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
#SuppressWarnings("unchecked")
private Class<T> getDomainClass() {
if (domainClass == null) {
ParameterizedType thisType =
(ParameterizedType) getClass().getGenericSuperclass();
this.domainClass =
(Class<T>) thisType.getActualTypeArguments()[0];
}
return domainClass;
}
private String getDomainClassName() {
return getDomainClass().getName();
}
public void create(T t) {
Method method = ReflectionUtils.findMethod(
getDomainClass(), "setDataCreazione",
new Class[] { Date.class });
if (method != null) {
try {
method.invoke(t, new Date());
} catch (Exception e) { /* Ignore */ }
}
getSession().save(t);
}
#SuppressWarnings("unchecked")
public T get(Serializable id) {
return (T) getSession().get(getDomainClass(), id);
}
#SuppressWarnings("unchecked")
public T load(Serializable id) {
return (T) getSession().load(getDomainClass(), id);
}
#SuppressWarnings("unchecked")
public List<T> getAll() {
return getSession()
.createQuery("from " + getDomainClassName())
.list();
}
public void update(T t) { getSession().update(t); }
public void delete(T t) { getSession().delete(t); }
public void deleteById(Serializable id) { delete(load(id)); }
public void deleteAll() {
getSession()
.createQuery("delete " + getDomainClassName())
.executeUpdate();
}
public long count() {
return (Long) getSession()
.createQuery("select count(*) from " + getDomainClassName())
.uniqueResult();
}
public boolean exists(Serializable id) { return (get(id) != null); }
}
HbnTestEntityDao class DAO
package it.cle.project.dao.hbn;
import it.cle.project.dao.TestEntityDao;
import it.cle.project.dao.hibernate.AbstractHbnDao;
import it.cle.project.model.TestEntity;
import java.util.List;
import org.springframework.stereotype.Repository;
#Repository
public class HbnTestEntityDao extends AbstractHbnDao<TestEntity> implements TestEntityDao {
#SuppressWarnings("unchecked")
public List<TestEntity> findByEmail(String email) {
return getSession()
.getNamedQuery("findContactsByEmail")
.setString("email", "%" + email + "%")
.list();
}
}
TestEntityService interface service
package it.cle.project.service;
import it.cle.project.model.TestEntity;
import java.util.List;
public interface TestEntityService {
void createTestEntity(TestEntity testEntity);
List<TestEntity> getListTestEntity();
List<TestEntity> getTestEntityByEmail(String email);
TestEntity getTestEntity(Integer id);
void updateTestEntity(TestEntity testEntity);
void deleteTestEntity(Integer id);
}
TestEntityServiceImpl
package it.cle.project.service.impl;
import it.cle.project.dao.TestEntityDao;
import it.cle.project.model.TestEntity;
import it.cle.project.service.TestEntityService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class TestEntityServiceImpl implements TestEntityService {
#Autowired
private TestEntityDao testEntityDao;
public void createTestEntity(TestEntity testEntity) {
testEntityDao.create(testEntity);
}
public List<TestEntity> getListTestEntity() {
return testEntityDao.getAll();
}
public List<TestEntity> getTestEntityByEmail(String email) {
return testEntityDao.findByEmail(email);
}
public TestEntity getTestEntity(Integer id) {
return testEntityDao.get(id);
}
public void updateTestEntity(TestEntity testEntity) {
testEntityDao.update(testEntity);
}
public void deleteTestEntity(Integer id) {
testEntityDao.deleteById(id);
}
}
Any ideas?
Thanks.
Your TestServiceImpl should be spring managed bean and should be fetched from Spring application context (by injection or by explicit asking the context). As the component scanning is at work, your TestServiceImpl is already managed with Spring's own supplied name (com...TestServiceImpl becomes testServiceImpl). You can give it your name like
#Service("myTestServiceImpl")
The instead of creating the bean yourself you can query this named bean from application context and use it.
That's some wall of text. I stopped at:
TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();
You created an unmanaged bean. Spring has no control over that. Put TestEntityServiceImpl into your spring context.

Resources