No Session found for current thread] when invoke Service method - spring

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.

Related

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();
}
}

LazyLoadInit exception with Spring + Spring JPA data + hibernate

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.

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

Spring EntityManager not persisting in standalone application

I'm having problems getting my EntityManager to persist my #Entity object in my standalone application. There are no errors, but nothing is persisted into the HSQL database.
I'm sure it must be something silly but i'm at my wits end with it now. I've searched and searched and tried everything but i still can't get it to work.
appconfig.xml:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" />
<bean id="productDaoImpl" class="test.ProductDao"/>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="test">
</context:component-scan>
persistence.xml:
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value=""/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:file://c:/db2"/>
</properties>
</persistence-unit>
</persistence>
EntityObj.java:
package test;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class EntityObj {
#Id
#GeneratedValue
private int id;
private String value;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
ProductDao.java:
package test;
import org.springframework.dao.DataAccessException;
public interface ProductDao {
public void save(EntityObj obj) throws DataAccessException;
}
ProductDaoImpl.java:
package test;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
public class ProductDaoImpl implements ProductDao {
#PersistenceContext
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Transactional (readOnly = false)
public void save(EntityObj obj)
{
try
{
entityManager.persist(obj);
entityManager.flush();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Main.java:
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Main {
public static void main(String[] args)
{
ApplicationContext springContext = new FileSystemXmlApplicationContext("classpath*:appconfig.xml");
ProductDao dao = (ProductDao) springContext.getBean("productDaoImpl");
EntityObj obj = new EntityObj();
obj.setValue("Blah");
dao.save(obj);
}
}
There are no errors whatsoever, it appears like it has saved the EntityObj but nothing is persisted in the database. I get the feeling it is transaction related and probably due to how i am instantiating the objects but i'm not sure.
The ENTITYOBJ database table is created automatically, just no data.

Resources