Hibernate: Best way of using the `SessionFactory` - java

I am developing a web application with pure JSP, Servlet and Hibernate. Last few days I was having a trouble with the SessionFactory of Hibernate, not knowing the best way of implementing it. In various places developers have claimed that there should be one SessionFactory for the application. So, I created a singleton class like below.
package dao;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class SessionFactoryBuilder
{
private static SessionFactoryBuilder instance;
private static SessionFactory sessionFactory;
private SessionFactoryBuilder()
{
buildConfig();
}
private static void buildConfig()
{
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactoryBuilder getInstance()
{
if(instance == null)
{
instance = new SessionFactoryBuilder();
}
return instance;
}
public SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
Below is a class which uses the SessionFactoryBuilder.
public class AgentImpl implements AgentInterface
{
SessionFactoryBuilder sessionFactory = SessionFactoryBuilder.getInstance();
#Override
public Session openCurrentSession() {
Session currentSession = sessionFactory.getSessionFactory().openSession();
return currentSession;
}
#Override
public Transaction openTransaction(Session session) {
Transaction beginTransaction = session.beginTransaction();
return beginTransaction;
}
#Override
public void save(Agent entity, Session session) {
session.save(entity);
}
#Override
public void update(Agent entity, Session session) {
session.update(entity);
}
}
Now my question is, is this is the best way of using the SessionFactory ? This might sound like a silly question but it will not when you think about multi threaded behavior in servlets, Driver#Connect error happening because of incorrect usage of session factory, various ways of implementing the singleton pattern and so on. Please provide me your advice.

Related

Getting exception java.lang.IllegalStateException: EntityManagerFactory is closed while trying to save secound istance

I am learning hibernate. Everything is preaty clear at the beegining, however when I try to run my app and in main I have two operation connected with session I get exception:
java.lang.IllegalStateException: EntityManagerFactory is closed
Below you can find my DBManager class where I habe methods for adding instances to DB:
import org.hibernate.Session;
public class DBManager
{
public void addAutor(String name, String lastName, Book book)
{
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Autor autor = new Autor(name,lastName,book);
session.save(autor);
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
public Book addBook(int ISBN, String name, String autorName)
{
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Book book = new Book(ISBN,name,autorName);
session.save(book);
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
return book;
}
}
Here is my HibernateUtil class for configuration of the session:
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Autor.class);
configuration.addAnnotatedClass(Book.class);
configuration.configure();
StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();
standardServiceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = standardServiceRegistryBuilder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
catch(Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
And finally the main class:
public class Test
{
public static void main (String args[])
{
DBManager dbManager = new DBManager();
Book book = dbManager.addBook(1,"Hobbit","Tolkien");
dbManager.addAutor("JRR","Tolkien",book);
}
}
As you can see I just put book, and than try to put Autor. What could be the reason for exception from secound method? I suppose that I do sth. wrong with closing and opening of the session, however I cannot figure out what is wrong.
I found the sulution myself:
I have created the one sessionFactory object for whole class DBManager:
private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
So in every method I open session, and than close at the end, eg:
public void addAutor(String name, String lastName, Book book)
{
Session session=sessionFactory.openSession();
session.beginTransaction();
Autor autor = new Autor(name,lastName,book);
session.save(autor);
session.getTransaction().commit();
session.close();
}
Maybe someone will face the same problem.

Spring AOP one method of a class before another

I have an app using Spring Core, Spring MVC, Hibernate.
There are a lot of DAO classes which get new Hibernate session in every method like this
#Autowired
private SessionFactory sessionFactory;
private Session session;
private void createSession() {
session = sessionFactory.openSession();
}
#Override
public List<User> listUsers() {
createSession();
List users;
users = session.createQuery("from User").list();
session.close();
return users;
}
I would like to use AOP to execute createSession method before those class methods but can't figure out how to do it.
All I have done was this aspect
#Configuration
#Aspect
public class DaoSessionLifeCycle {
#Before(value = "execution(* ua.com.alistratenko.dao.UserDaoImp.listUsers(..))")
public void openSession(JoinPoint joinPoint){
System.out.println("izi");
}
}
Because you still did not provide an MCVE or at least some more (and more realistic) sample code, I can only speculate and provide a schematic answer.
BTW, I am using AspectJ and not Spring AOP here, but it should work the same way there.
Dummy classes to make the sample code compile:
package ua.com.alistratenko.dao;
public class User {
String name;
public User(String name) {
this.name = name;
}
#Override
public String toString() {
return "User [name=" + name + "]";
}
}
package ua.com.alistratenko.dao;
import java.util.ArrayList;
import java.util.List;
public class QueryResult {
public List<User> list() {
List<User> users = new ArrayList<>();
users.add(new User("jane"));
users.add(new User("joe"));
return users;
}
}
package ua.com.alistratenko.dao;
public class Session {
public QueryResult createQuery(String string) {
return new QueryResult();
}
public void close() {}
}
package ua.com.alistratenko.dao;
public class SessionFactory {
public Session openSession() {
return new Session();
}
}
Application class:
What did I change?
In Spring you would use #Autowired instead of creating the session factory by yourself. I just did this in order to be able to run my sample code without Spring.
Added some setters/getters for the aspect to be able to access the session factory and also the session itself
Removed createSession() (code migrated to aspect, see below)
No more boilerplate clutter in listUsers()
Added main method for demo purposes
package ua.com.alistratenko.dao;
import java.util.List;
public class UserDaoImp {
private SessionFactory sessionFactory = new SessionFactory();
private Session session;
public SessionFactory getSessionFactory() { return sessionFactory; }
public Session getSession() { return session; }
public void setSession(Session session) { this.session = session; }
public List<User> listUsers() {
return session.createQuery("from User").list();
}
public static void main(String[] args) {
new UserDaoImp().listUsers();
}
}
Aspect:
In order to do something before + after the intercepted method call, please use #Around.
package de.scrum_master.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
//import org.springframework.stereotype.Component;
import ua.com.alistratenko.dao.UserDaoImp;
//#Component
#Aspect
public class DaoSessionLifeCycle {
#Around("execution(public * listUsers(..)) && target(dao)")
public Object openSession(ProceedingJoinPoint thisJoinPoint, UserDaoImp dao) throws Throwable {
try {
System.out.println("Creating session");
dao.setSession(dao.getSessionFactory().openSession());
System.out.println("Calling " + thisJoinPoint.getSignature());
return thisJoinPoint.proceed();
}
finally {
try {
System.out.println("Closing session");
dao.getSession().close();
}
catch (Exception e) {}
}
}
}
Console log:
Creating session
Calling List ua.com.alistratenko.dao.UserDaoImp.listUsers()
Closing session
Now there are several open questions:
Do you only want to handle this one class or maybe all subclasses of a base class or an implemented interface common to all your DAOs? Then the pointcut would look different.
Do you only want to intercept method listUsers() or maybe also other methods? As you did not show more code, nobody except you can know. The pointcut would also look different depending on your answer.
Do you really want to do this all manually or maybe follow the other users' advice and use on-board Spring tools in order to manage your transactions? I have no idea about Spring, so I cannot tell you. I was just providing the answer to your question which was aspect-related.
In addition to what #Bogdan says, take a look at CrudRepository or JpaRepository, it will save you a lot of time. Also, in my opinion, #Aspect classes are annotated with #Component as opposed to #Configuration.

Hibernate issue with `SessionFactory`

I am having a JSP, Servlet (Pure JSP, Servlet) application where it uses Hibernate. Below is a Hibernate implementation class for a one table.
DesignationImpl.java
package dao;
import model.sub.DesigAllBean;
import java.util.List;
import model.main.Designation;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
/**
*
* #author Yohan
*/
public class DesignationImpl implements DesignationInterface
{
#Override
public Session openCurrentSession() {
Session currentSession = getSessionFactory().openSession();
return currentSession;
}
#Override
public Transaction openTransaction(Session session) {
Transaction beginTransaction = session.beginTransaction();
return beginTransaction;
}
private static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
return sessionFactory;
}
#Override
public void save(Designation d, Session session)
{
session.save(d);
}
#Override
public void update(Designation d, Session session)
{
session.update(d);
}
}
Below is the service class which calls to the above class.
DesignationService .java
package service;
import dao.Common;
import model.sub.*;
import dao.DesignationImpl;
import dao.DesignationInterface;
import java.util.ArrayList;
import java.util.List;
import model.main.Designation;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* #author Yohan
*/
public class DesignationService
{
private DesignationInterface designationInterface;
public DesignationService()
{
designationInterface = new DesignationImpl();
}
public Session getSession()
{
Session session = designationInterface.openCurrentSession();
return session;
}
public Transaction getTransaction(Session session)
{
return designationInterface.openTransaction(session);
}
public String save(Designation d)
{
Session session = designationInterface.openCurrentSession();
Transaction transaction = null;
String result="";
try
{
transaction = designationInterface.openTransaction(session);
designationInterface.save(d,session);
transaction.commit();
result = Common.SAVE_SUCCESS;
}
catch(Exception e)
{
e.printStackTrace();
if(transaction!=null)
{
transaction.rollback();
}
result = Common.SAVE_ROLLBACK;
}
finally
{
session.close();
}
return result;
}
public String update(Designation d)
{
Session session = designationInterface.openCurrentSession();
Transaction transaction = null;
String result="";
try
{
transaction = designationInterface.openTransaction(session);
designationInterface.update(d,session);
transaction.commit();
result = Common.SAVE_SUCCESS;
}
catch(Exception e)
{
e.printStackTrace();
if(transaction!=null)
{
transaction.rollback();
}
result = Common.SAVE_ROLLBACK;
}
finally
{
session.close();
}
return result;
}
}
And the servlets call them like below.
DesignationService desigSrvc=new DesignationService();
Designation designation=desigSrvc.findByForiegnKey(idEmployee);
Employee empl=new Employee();
empl.setIdEmployee(idEmployee);
if(designation.getDateCreated()==null)
{
designation.setDateCreated(Common.getCurrentDateSQL());
}
designation.setEmployee(empl);
designation.setDesignation(txtDesignation);
designation.setLocation(location);
designation.setSalary(salary);
designation.setDatePromoted(datePromoted);
designation.setLastUpdated(Common.getCurrentDateSQL());
desigSrvc.save(designation);
As you can see, there is a bad thing happening there, that is, the servlets are creating new SessionFactory instances every time it executes.I am having Driver#Connect issues and I guess this might be the reason for it.
I read stackoverflow posts and some seems to be suggesting the use of only one SessionFactory for the entire application. If it is suitable, then how can I do it? Maybe make a singleton class like below and use it in my implementation classes?
public class SessionFactoryBuilder
{
private static SessionFactoryBuilder instance;
private static SessionFactory sessionFactory;
private SessionFactoryBuilder()
{
}
private static void buildConfig()
{
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactoryBuilder getInstance()
{
if(instance == null)
{
instance = new SessionFactoryBuilder();
buildConfig();
}
return instance;
}
public SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
But then what about threads? Servlets are multi threaded isn't it?
As I commented I have the HibernateUtil.java class as Singleton. This class can provide you sessionfactory using HibernateUtil.getSessionFactory() and you should remove the related code from your DesignationImpl class
public class HibernateUtil {
private static StandardServiceRegistry serviceRegistry;
private static SessionFactory INSTANCE = null;
public static SessionFactory getSessionFactory() {
if(INSTANCE=null){
createSessionFactory():
}
return sessionFactory;
}
private synchronized static void createSessionFactory(){
if(INSTANCE!=null){return;}
Configuration configuration = new Configuration();
configuration.configure();
SeviceRegistry=newStandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
}
}
Find the above code, and please suggest / comment to confirm the correctness of code.I think threading will be taken care of using this..I adding a dual check to avoid multiple sessionfactory creation ad its a heavy resource.
I corrected Viraj Nalawade's code which had a few errors:
class HibernateUtil {
private static SessionFactory INSTANCE = null;
public static SessionFactory getSessionFactory() {
if (INSTANCE == null) {
createSessionFactory();
}
return INSTANCE;
}
private synchronized static void createSessionFactory() {
if (INSTANCE != null) {
return;
}
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = configuration.getStandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
INSTANCE = configuration.buildSessionFactory(serviceRegistry);
}
}

Hibernate, Spring, querying in non-managed bean causes SessionException

I have a simple entity - Team, with name and rating properties (or maybe more).
Suppose I need to query my teams by multiple criteria.
So instead of adding multiple methods with signature like 'findByXYZAndZYX' to my service, I'd rather add following method :
Teams findTeams()
Implementation snippet:
#Autowired private SessionFactory sessionFactory;
...
#Override
public Teams getTeams() {
return new HibernateTeams(sessionFactory);
}
Now, Teams interface:
public interface Teams extends Iterable<Team> {
Teams withNameContaining(String name);
Teams withRatingGreaterThan(Integer rating);
}
and hibernate-specific implementation:
public class HibernateTeams implements Teams {
private static final String NAME_PROPERTY = "name";
private static final String RATING_PROPERTY = "rating";
private SessionFactory sessionFactory;
private Criteria criteria;
public HibernateTeams(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
criteria = getRootCriteria();
}
private Criteria getRootCriteria() {
return getCurrentSession().createCriteria(Team.class);
}
#Override
public HibernateTeams withNameContaining(String name) {
criteria.add(Restrictions.like(NAME_PROPERTY, name));
return this;
}
#Override
public Teams withRatingGreaterThan(Integer rating) {
criteria.add(Restrictions.gt(RATING_PROPERTY, rating));
return this;
}
#Override
public Iterator<Team> iterator() {
#SuppressWarnings("unchecked")
Collection<Team> result = criteria.list();
return result.iterator();
}
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}
But now, using this in client code:
teamService
.getTeams()
.withNameContaining("someTeamName")
.withRatingGreaterThan(15)
I have an SessionException
org.hibernate.SessionException: Session is closed
I suppose this happens because of passing sessionFactory to non-managed class.
So there are a couple of questions here:
1) Is it possible to do this the way I wrote it? I tried to annotate my HibernateTeams with Transactional or sth, but it didn't help.
2) If I need to make my HibernateTeams spring-managed-bean and possibly inject SessionFactory into it, how can I do that? I've already tried with
#Component #Scope("prototype")
or #Configurable
but with no luck.
Thanks,

Spring Annotations -java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required in spring+hibernate

I am getting the error as in the question. My Dao Implement Class is as follows :
package com.argus.intenew;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
#Autowired
AnnotationSessionFactoryBean sessionFactory;
public UserDaoImpl() {
}
public AnnotationSessionFactoryBean getCurrentSessionFactory() {
return sessionFactory;
}
public void setCurrentSessionFactory(AnnotationSessionFactoryBean sessionfactory) {
this.sessionFactory = sessionfactory;
}
#Override
public void addUser(UserMap userMap) {
System.out.println("33333333333333333333");
getHibernateTemplate().save(userMap);
}
#Override
public List<User> findAllUser() {
return getHibernateTemplate().find("from User");
}
#Override
public void deleteUser(UserMap user) {
getHibernateTemplate().delete(user);
}
#Override
public void updateUser(UserMap user) {
getHibernateTemplate().update(user);
}
}
And my configuration class is as follows:
package com.argus.intenew;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
#Configuration
#ComponentScan(basePackages = {"com.argus.intenew"})
public class Webconfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "org.hibernate.dialect.MySQLDialect ";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "true";
#Bean
public DataSource dataSource() {
System.out.println("----------InDATAsource------------");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/MyUser");
dataSource.setUsername("root");
dataSource.setPassword("XXX");
System.out.println("----------OutofDATAsource------------");
return dataSource;
}
#Bean
public AnnotationSessionFactoryBean sessionFactory() {
System.out.println("----------InsessionFactory------------");
AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
String[] pckage={"com.argus.intenew"};
sessionFactory.setPackagesToScan(pckage);
sessionFactory.setHibernateProperties(hibProperties());
System.out.println("----------Outof session------------");
return sessionFactory;
}
private Properties hibProperties() {
System.out.println("----------InhipProp------------");
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, "org.hibernate.dialect.MySQLDialect ");
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, "true");
System.out.println("----------outofhip------------");
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory().getObject());
return transactionManager;
}
#Bean
public UserBoImpl userBo() {
System.out.println("----------InUserBo------------");
UserBoImpl userBo= new UserBoImpl();
userBo.setUserDao(userDao());
System.out.println("----------OutofUserbo------------");
return userBo;
}
#Bean
public UserDaoImpl userDao() {
System.out.println("----------InUserDao------------");
UserDaoImpl userDao=new UserDaoImpl();
userDao.setCurrentSessionFactory(sessionFactory());
System.out.println("----------OutofUserDao------------");
return userDao;
}
}
Anyone please help and tell me what is the correct way to do this with annotations.
Here I am not using any xml file.
Your DAO implementation is not leveraging its superclass correctly.
You're injecting a Spring FactoryBean<SessionFactory> when it really needs a Hibernate SessionFactory.
It's not actually using the injected dependency.
You're attempting to use HibernateDaoSupport#getHibernateTemplate() without giving it a reference to a SessionFactory or a HibernateTemplate.
Note that HibernateDaoSupport will create its own HibernateTemplate as long as you give it a SessionFactory.
I suggest you make the following changes:
Remove AnnotationSessionFactoryBean sessionFactory from UserDaoImpl
Fix configuration of UserDaoImpl by leveraging its inherited setSessionFactory(SessionFactory) method
So you actually end up with this DAO code:
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
#Override
public void addUser(UserMap userMap) {
getHibernateTemplate().save(userMap);
}
#Override
public List<User> findAllUser() {
return getHibernateTemplate().find("from User");
}
#Override
public void deleteUser(UserMap user) {
getHibernateTemplate().delete(user);
}
#Override
public void updateUser(UserMap user) {
getHibernateTemplate().update(user);
}
}
And this configuration code:
#Configuration
#ComponentScan(basePackages = {"com.argus.intenew"})
public class Webconfig {
//snip...
#Bean
public UserDaoImpl userDao() {
UserDaoImpl userDao=new UserDaoImpl();
userDao.setSessionFactory(sessionFactory().getObject());
return userDao;
}
}
Note that it's ok to return the FactoryBean from the sessionFactory() configuration method since Spring will detect and utilize its lifecycle methods (via InitializingBean and DisposableBean), but you need to accommodate by calling the FactoryBean method getObject() yourself.
Don't user HibernateDaoSupport and/or HibernateTemplate. With the release of Hibernate 3.0.1 that support should be regarded deprecated. As mentioned in the reference guide implement the dao/repository based on plain hibernate.
Your dao will look like
#Repository
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(UserMap userMap) {
System.out.println("33333333333333333333");
sessionFactory.getCurrentSession().save(userMap);
}
#Override
public List<User> findAllUser() {
return sessionFactory.getCurrentSession().createQuery("from User").list();
}
#Override
public void deleteUser(UserMap user) {
sessionFactory.getCurrentSession().delete(user);
}
#Override
public void updateUser(UserMap user) {
sessionFactory.getCurrentSession().update(user);
}
}
As you are already using the #ComponentScan annotation (and I assume yo have your BO annotated with #Service and properly annotated with #Autowired there is no need to explictly configure you dao and service in the configuration.
#Configuration
#ComponentScan(basePackages = {"com.argus.intenew"})
public class Webconfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "org.hibernate.dialect.MySQLDialect ";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "true";
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/MyUser");
dataSource.setUsername("root");
dataSource.setPassword("XXX");
return dataSource;
}
#Bean
public AnnotationSessionFactoryBean sessionFactory() {
AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
String[] pckage={"com.argus.intenew"};
sessionFactory.setPackagesToScan(pckage);
sessionFactory.setHibernateProperties(hibProperties());
return sessionFactory;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, "org.hibernate.dialect.MySQLDialect ");
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, "true");
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
return new HibernateTransactionManager(sessionFactory().getObject());
}
}
A note regarding DriverManagerDataSource this is nice for testing but please don't use this in production (unless you want an application that doesn't perform). Use a proper JDBC Connection Pool instead.
A final note, if you really want productivity drop hibernate, switch to JPA and use Spring Data JPA for your repositories. Saves you writing a lot of implementation code. (And the best maintainable and testable code is code not written :) ).

Categories

Resources