Hibernate Session is closed in spring transaction after calling method second time - java

First of all I am a beginner in spring.I have created a simple Spring service that has DAO injected and transaction is managed by HibernateTransactionManager of spring, like as below.(And transaction configuration is used using annotations )
#Service(value="daopowered")
public class UserServiceImplDao implements UserService
{
#Inject
private UserDao userDao;
#Override
#Transactional
public User autheticate( String userId, String password )
{
return userDao.findByIdAndPassword(userId, password);
}
My transaction configuration is following
<bean id="txMgr"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="txMgr" />
Now the problem is when I call authenticate method first time using some controller then it works fine ( does DB operations successfully) but after calling it again second time hibernate session is closed exception is coming ? Please guide me what I am doing it wrong or how to handle this scenario ? Why wont spring opens a new transaction when I call this method second time ?
Exception Trace:
2013-05-22T21:04:18.041+0530 DEBUG [14208212-2] lerExceptionResolver Resolving exception from handler [com.akhi.store.controller.HomeController#5d9d277e]: org.springframework.orm.hibernate3.HibernateSystemException: Session is closed!; nested exception is org.hibernate.SessionException: Session is closed!
2013-05-22T21:04:18.044+0530 DEBUG [14208212-2] tusExceptionResolver Resolving exception from handler [com.akhi.store.controller.HomeController#5d9d277e]: org.springframework.orm.hibernate3.HibernateSystemException: Session is closed!; nested exception is org.hibernate.SessionException: Session is closed!
2013-05-22T21:04:18.044+0530 DEBUG [14208212-2] lerExceptionResolver Resolving exception from handler [com.akhi.store.controller.HomeController#5d9d277e]: org.springframework.orm.hibernate3.HibernateSystemException: Session is closed!; nested exception is org.hibernate.SessionException: Session is closed!
2013-05-22T21:04:18.046+0530 DEBUG [14208212-2] et.DispatcherServlet Could not complete request
org.springframework.orm.hibernate3.HibernateSystemException: Session is closed!; nested exception is org.hibernate.SessionException: Session is closed!
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:658)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.convertHibernateAccessException(AbstractSessionFactoryBean.java:245)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.translateExceptionIfPossible(AbstractSessionFactoryBean.java:224)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy28.findByIdAndPassword(Unknown Source)
EDIT: The DAO code
#Repository
public class UserDaoImpl extends GenericHibernateDAO<User, Long>
implements
UserDao
{
#Override
public User findByIdAndPassword( String id, String password )
{
Criteria crit = getSession().createCriteria(User.class).add(Restrictions.eq("userId",
id)).add(Restrictions.eq("password",
password)).setMaxResults(1);
List<?> list = crit.list();
if (list.size() > 0)
return (User) list.get(0);
else
return null;
}
and getSession() implementation is
protected Session getSession() {
if (session == null) {
session = sessionFactory.getCurrentSession();
}
return session;
}
Also the abstract DAO class has sessionfactory injected
public abstract class GenericHibernateDAO<T, ID extends Serializable>
implements GenericDAO<T, Long> {
private Class<T> persistentClass;
protected Session session;
#Autowired
private SessionFactory sessionFactory;

Your ObjectDao need a SessionFactory and the annotation Transaction. Something like this :
#Component
public class userDao{
#AutoWired
private SessionFactory sessionFactory;
#Transactional
public User findByIdAndPassword(String id , String password){
....
}
{getters and setters}
}
Dont do that :
protected Session getSession() {
if (session == null) {
session = sessionFactory.getCurrentSession();
}
return session;
}
just return the current session , the Transactional annotation is responsible for opening and closing sessions , like this :
protected Session getSession() {
return sessionFactory.getCurrentSession();
}

Related

How to Update an Entity from a Thread in Dropwizard, Hibernate

I have a thread that waits until a process is complete and then needs to update an entity. But I get
Exception in thread "Thread-22" org.hibernate.HibernateException: No session currently bound to execution context
I have tried opening a new session (see the code below). Session management is normally handled by #UnitOfWork, but this annotation seems to apply only to resources.
public class ConfigDAO extends AbstractDAO<Config>
{
private final SessionFactory sessionFactory;
public ConfigDAO(SessionFactory factory) {
super(factory);
this.sessionFactory = factory;
}
public Config updateFromNewSession(Config config) {
System.out.print("current session: ");
Session session = sessionFactory.openSession();
System.out.println(session);
session.persist(config);
session.close();
return config;
}

How to prevent implicit caching in Spring Boot 1.5.1 Hibernate

I am trying to understand why, after creating a new entity and persisting it whilst the application is running, when retrieving a list of these entities, the new entity should be retrieved from the database, but isn't?
For example:
I created a new entity (from the UI) and persisted it successfully like so:
#Repository
public class BaseDAOHibernate {
Session session;
public BaseDAOHibernate() {
session = HibernateUtils.getSessionFactory().openSession();
}
public void save(Object object) {
Transaction tx = session.beginTransaction();
session.save(object);
tx.commit();
}
...
I verified that the entity is persisted in the database.
Next, when I refresh the UI which lists these entities (for which I added a new one to the database) the new entity is not included and was not retrieved from the following:
#Repository
#SuppressWarnings("unchecked")
public class PasswordDAOHibernate extends BaseDAOHibernate implements PasswordDAO {
#Override
public Collection<Password> getPasswords() {
Query query = session.createQuery("select ...");
return query.list();
}
Here is the interface:
public interface PasswordDAO {
Password getPassword(Integer id);
Collection<Password> getPasswords();
Collection<Password> getPasswords(PasswordSearchParameters params);
Collection<PasswordType> getPasswordTypes();
}
...
Which is called from a controller:
#Controller
public class PasswordsController extends BaseControllerHelper {
#Autowired
private PasswordDAOHibernate passwordDAO;
#RequestMapping("/passwords.htm")
public void passwords(Map model,
HttpServletRequest request) {
Collection<Password> passwords = passwordDAO.getPasswords();
model.put("passwords", passwords);
}
Here is the configuration currently setup:
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:mysql://host:3306/server</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.crm.entity.User"></mapping>
<mapping class="com.crm.entity.Role"></mapping>
<mapping class="com.crm.entity.Property"></mapping>
<mapping class="com.crm.entity.Menu"></mapping>
<mapping class="com.crm.entity.Password"></mapping>
<mapping class="com.crm.entity.PasswordType"></mapping>
</session-factory>
</hibernate-configuration>
HibernateUtils.java
#Component
public class HibernateUtils {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
When I restart the server application the new entity displays in the list.
Is there some kind of implicit caching going on that I need to clear? Note, I have not implemented any explicit caching at this stage.
The problem is your dao, which is flawed in a very dangerous way. A Session isn't thread safe and shouldn't be shared. It should be opened for each action (or at least the current session should be used).
Plain Hibernate Solution
You DAO should look something like this.
private final SessionFactory sessionFactory;
protected BaseDAOHibernate(SessionFactory sessionFactory) {
this.sessionFactory=sessionFactory;
}
protected Session getSession() {
return this.sessionFactory.getCurrentSession();
}
public void save(Object object) {
getCurrentSession().save(object);
}
Now you specific dao should reuse the getSession method.
#Repository
#Transactional
public class PasswordDAOHibernate extends BaseDao implements PasswordDao {
#Autowired
public PasswordDAOHibernate(SessionFactory sessionFactory) {
super(sessionFactory);
}
#Override
public Collection<Password> getPasswords() {
return getSession.query("select ...", Password.class).list();
}
When doing so you probably will run into issues with an error stating that no session can be found due to no transaction (or something along those lines).
To fix this use Spring Boot (and some manual configuration).
First move the hibernate.connection properties to your application.properties and remove them from hibernate.cfg.xml.
spring.datasource.url=jdbc:mysql://host:3306/server
spring.datasource.username=username
spring.datasource.password
Now Spring will create a Datasource for you. Next remove your HibernateUtils and configure the SessionFactory using Springs LocalSessionFactoryBean.
#Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(dataSource);
return factory;
}
You will also need the appropriate transaction manager
#Bean
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
return new HibernateTransactionManager(sessionFactory);
}
Now due to everything being setup in Spring, the injection of the SessionFactory and the #Transactional you will get a managed Session which will be properly opened and closed for you.
Controller Fix
Your controller is also flawed as you should be injecting a PasswordDao and not the concrete type (which would now fail due the the creation of a proxy for the transactions).
#Controller
public class PasswordsController extends BaseControllerHelper {
#Autowired
private PasswordDAO passwordDAO;
JPA Solution
However while all of this will probably work I would strongly suggest to use JPA and the EntityManager instead of the Session and SessionFactory approach.
To do so remove the LocalSessionFactoryBean and the HibernateTransactionManager and add the remaining properties of the hibernate.cfg.xml to the application.properties.
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true
Next to the spring.datasource properties that is all you need and you can delete the hibernate.cfg.xml file.
Now instead of using the SessionFactory use the EntityManager in your dao.
public abstract class BaseDao {
#PersistenceContext
protected EntityManager em;
public void save(Object o) {
em.persist(o);
}
}
And your specific dao.
#Repository
#Transactional
public PasswordJpaDao extends BaseDao implements PasswordDao {
#Override
public Collection<Password> getPasswords() {
return em.createQuery("select ...", Password.class).getResultList();
}
Spring Data JPA Solution
When using JPA you could even drop your generic dao approach and implementations and use Spring Data JPA instead. Your whole PasswordDao would then look like
public interface PasswordDao extends JpaRepository<Password, Long> {}
All the crud functionality (findAll, findOne, save etc.) is available out-of-the-box. Creating queries is pretty easy and saves you from writing the boilerplate code.
You can use #Cacheable(false) on your entity
or disable the shared cache altogether for all your entities by adding this to your persistence.xml
<shared-cache-mode>NONE</shared-cache-mode>
For Hibernate you can also use
session.setCacheMode(CacheMode.IGNORE);
see this link for more information about the different cache levels in JPA

why do Iget closed session outside of spring Context

I'm trying to configure spring with hibernate, and I noticed one thing I can not get: when I tryied to get Session object from Container.
Bean.getBean(GenericDao.class).getCurrentSession(); I can only get closed session.
If I will do same with openSession() method - I would receive valid session.
So the question is next: why? I ve been researching in google, but did not find answer. Do anybody knows?
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
#Transactional ( propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class } )
public abstract class GenericDao {
#Autowired
protected SessionFactory sessionFactory;
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public Session openSession() {
return sessionFactory.openSession();
}
public void saveOrUpdate(final Serializable object) {
getCurrentSession().saveOrUpdate(object);
}
public void delete(final Serializable object) {
getCurrentSession().delete(object);
}
public void save(final Serializable object) {
getCurrentSession().save(object);
}
public void update(final Serializable object) {
getCurrentSession().update(object);
}
public void merge(final Serializable object) {
getCurrentSession().merge(object);
}
#SuppressWarnings ( "unchecked" )
public <T> List<T> list(final Class<T> clazz) {
return getCurrentSession().createCriteria(clazz).list();
}
#SuppressWarnings ( "unchecked" )
public <T> T get(final Class<T> clazz, final Serializable id) {
return (T) getCurrentSession().get(clazz, id);
}
}
#Repository
#Primary
class GenericDaoImpl extends GenericDao {
}
1) This is because, using getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file as below.
<property name="hibernate.current_session_context_class">thread</property>
thread context means current thread. The default value is jta context means an already existing jta transaction.
Since this session object (fetched using getCurrentSession()) belongs to the hibernate context, we don’t need to close it. Once the SessionFactory is closed, this session object gets closed.
The getCurrentSession() should be used for single threaded environment.
2) openSession() method always opens a new session. We should close this session object once we are done with all the database operations.
We should open a new session for each request in multi-threaded environment.
For more details related to thread safety and Hibernate Session & their usage, please see this.
Hibernate uses a the notion of current context class to determine the scope of the Session to use with getCurrentSession(). In pure Hibernate this can be thread whereby the Session is bound to the thread , jta where the session is bound to a JTA UserTransaction
When used with Spring you dont need to specify the hibernate.current_session_context_class property as Spring uses its own called SpringSessionContext. This binds the session to the ongoing transaction using whatever PlatformTransactionManager you are using
To use SessionFactory.getCurrentSession() make sure your call is inside a #Transactional method otherwise it wont work and you have to open the session manually using openSession()
#Transactional takes responsibility for opening and closing sessionFactory, you can use getCurrentSession without openSession as:
#SuppressWarnings ( "unchecked" )
public <T> List<T> list(final Class<T> clazz) {
return getCurrentSession().createCriteria(clazz).list();
}
if you configured transaction with #Annotation or in .xml file as here:
<bean id="sessionFactory" class="..."</bean>
<tx:annotation-driven proxy-target-class="true" transaction-manager="txManager" />
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
and with #Transational and #Autowired as you do, it is ok
If you don't configure transaction, you can use openSession() only, and add closeSession when you want to finish session

What is the difference between 'getDelegate()' and 'unwrap()' for getting the Hibernate session of an entity manager

To speed up iteration of all rows in a SQL table using Hibernate (since JPA doesn't support streaming), I followed the approach of this answer. While this works well, this answer tells us that we should retrieve the Session object using
Session session = entityManager.unwrap(Session.class);
instead of the way it was done in the answer:
Session session = (Session) manager.getDelegate();
Hower, with this change I suddenly get the following exception:
java.lang.IllegalStateException: No transactional EntityManager available
The entity manager is autowired into a field in a Spring component like this:
#Component
public class Updater {
#Autowired
private EntityManager entityManager;
#Transactional
public void update() {
// ...
Result loadedResult = loadAll()
// ...
}
private Result loadAll() {
Session session = (Session) manager.getDelegate();
//Session session = entityManager.unwrap(Session.class);
SessionFactory sessionFactory = session.getSessionFactory();
StatelessSession statelessSession = sessionFactory.openStatelessSession();
// ... #linked answer ...
}
}
As the name suggests, loadAll only reads data and transforms it into some Result. update does write to the database.
Note that loadAll is only called through update. Also, annotating loadAll with #Transactional doesn't fix the problem.
I know there are several other questions regarding this error, stating #Transactional to be the answer. My question is what the difference between getDelegate and unwrap really is: Why does the one fail and the other not? (And why doesn't #Transactional fix the problem?)
I'm using H2 1.4.190 and Hibernate 4.3.11.Final (through Spring Boot 1.3.2.RELEASE).
EDIT Full minimal example (with package declarations and imports omitted). All classes are in package com.example:
Entity.java
#javax.persistence.Entity
public class Entity {
#Id
#GeneratedValue
public int id;
public int value;
}
EntityRepository.java
public interface EntityRepository extends JpaRepository<Entity, Integer> {
}
Config.java:
#Configuration
#ComponentScan
#EnableJpaRepositories
#EntityScan
#EnableTransactionManagement
public class Config {
}
Runner.java:
#SpringBootApplication
public class Runner implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(Runner.class);
application.setWebEnvironment(false);
application.run(args);
}
#Autowired
private Updater updater;
#Override
public void run(String... args) throws Exception {
updater.insert(1, 4, 2);
updater.update();
updater.printAll();
}
}
Updater.java:
#Component
public class Updater {
#Autowired
private EntityRepository repository;
#PersistenceContext //#Autowired
private EntityManager entityManager;
public void insert(int... values) {
for (int value : values) {
Entity entity = new Entity();
entity.value = value;
repository.save(entity);
}
repository.flush();
}
public void update() {
// Call "transactioned" method through an intermediary method.
// The code works if 'Runner' calls 'transactionedUpdate' directly.
transactionedUpdate();
}
#Transactional
public void transactionedUpdate() {
int sum = loadAll();
// Set all 'value's to 'sum'.
List<Entity> entities = repository.findAll();
for (Entity entity : entities) {
entity.value = sum;
repository.save(entity);
}
repository.flush();
}
public int loadAll() {
// Session session = (Session) entityManager.getDelegate();
Session session = entityManager.unwrap(Session.class);
SessionFactory sessionFactory = session.getSessionFactory();
StatelessSession statelessSession = sessionFactory.openStatelessSession();
Query query = statelessSession.createQuery("FROM com.example.Entity e");
query.setFetchSize(1000);
query.setReadOnly(true);
query.setLockMode("e", LockMode.NONE);
ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
int sum = 0;
while (results.next()) {
Entity entity = (Entity) results.get(0);
sum += entity.value;
}
results.close();
statelessSession.close();
return sum;
}
public void printAll() {
List<Entity> entities = repository.findAll();
for (Entity entity : entities) {
System.out.println(entity.id + ": " + entity.value);
}
}
}
application.yml:
spring:
jpa:
open-in-view: false
hibernate:
ddl-auto: update
naming-strategy: org.springframework.boot.orm.jpa.hibernate.SpringNamingStrategy
database: H2
show_sql: false
properties:
hibernate.cache.use_second_level_cache: true
hibernate.cache.use_query_cache: false
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:file:~/data-test/db;DB_CLOSE_DELAY=-1
name:
username: test
password:
Stack trace:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:809) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:790) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:777) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at com.example.Runner.main(Runner.java:16) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_60]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_60]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_60]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_60]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) [idea_rt.jar:na]
Caused by: java.lang.IllegalStateException: No transactional EntityManager available
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:268) ~[spring-orm-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at com.sun.proxy.$Proxy49.unwrap(Unknown Source) ~[na:na]
at com.example.Updater.loadAll(Updater.java:49) ~[classes/:na]
at com.example.Updater.doUpdate(Updater.java:36) ~[classes/:na]
at com.example.Updater.update(Updater.java:31) ~[classes/:na]
at com.example.Updater$$FastClassBySpringCGLIB$$503dcdb8.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at com.example.Updater$$EnhancerBySpringCGLIB$$f362c2c8.update(<generated>) ~[classes/:na]
at com.example.Runner.run(Runner.java:25) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:806) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
... 9 common frames omitted
Well, I'm not using Spring, but when I wanted to get the SessionFactory for performance reasons I simply declared it in a Stateless EJB:
#Stateless
public class OpinionViewCache {
#PersistenceUnit(unitName="opee") SessionFactory sessionFactory;
private StatelessSession statelessSession;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
And to get session I used a simple call:
statelessSession = sessionFactory.openStatelessSession();
Closed it when I was done:
statelessSession.close();
Otherwise the code I used for testing from Java SE was pretty straight forward:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("opjpa");
EntityManager em = emf.createEntityManager();
EntityManagerImpl emImpl = (EntityManagerImpl)em;
HibernateEntityManagerFactory factory = emImpl.getFactory();
SessionFactory sessionFactory = factory.getSessionFactory();

PropertyPlaceholderConfigurer break my hibernate session

I have an issue in my Spring project when, after create my hibernateSession and TransactionManager I initilize a bean that extends PropertyPlaceholderConfigurer
I dont know why but in that moment my hibermnate session is ruin to be used for the rest of my DAO´s. The error that is throwing is this one.
Caused by: org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
Any suggestions?
I´m trying to extract from database some data to create a properties class and set to a class that I´ve create that extends PropertyPlaceholderConfigurer
This is the class
public class PropertiesSourceImpl extends PropertyPlaceholderConfigurer{
public ConfigurationSource configurationSource;
public Properties properties;
public void init() {
for (ConfigurationProperty prop : configurationSource.getEnabledConfigurationPropertiesByType(ConfigurationProperty.PropertyType.MAIL)) {
System.out.println(prop);
// properties.setProperty(prop.getPropertyKey(), prop.getPropertyValue());
}
}
public Properties getProperties() {
return properties;
}
#Required
public void setConfigurationSource(final ConfigurationSource configurationSource) {
this.configurationSource = configurationSource;
}
}
and here my bean definition
<bean id="propertiesSource" class="nl.greenvalley.digipolis.config.PropertiesSourceImpl" init-method="init">
<property name="configurationSource" ref="configurationSource"/>
</bean>
Finally I found a solution. Instead of use hibernate I just create a new session and transaction before the hibernate session and transaction would be created.
SessionFactory sessionFactory;
public void init() {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
Properties properties = new Properties();
tx = session.beginTransaction();
List<ConfigurationProperty> dbProperties = session.createCriteria(ConfigurationProperty.class).list();
for (ConfigurationProperty property : dbProperties) {
properties.setProperty(property.getPropertyKey(), property.getPropertyValue());
}
setProperties(properties);
tx.commit();
} finally {
session.close();
}
}

Categories

Resources