In the hibernate documentation for version 4.3.0.Final the following code snippet is given to create a SessionFactory:
package org.hibernate.tutorial.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
This seems to be outdated, as the method buildSessionFactory() is deprecated. What is the correct way to create the SessionFactory?
public class TestHB4 {
private static StandardServiceRegistry serviceRegistry;
private static SessionFactory sessionFactory;
public static void main(String[] args) {
Person person = new Person();
person.setFirstName("Namal");
person.setLastName("Dinesh");
Configuration configuration = new Configuration().configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.configure().buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
session.close();
}
Related
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory(){
StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().
loadProperties("hibernate.properties").build();
Metadata metadata = new MetadataSources(standardServiceRegistry)
.addAnnotatedClass(Student.class)
.addAnnotatedClass(Course.class)
.getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
Its not working. I also want to configure hibernate using property file (well known to xml configuration).
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.
I have JSF maven project with Hibernate. There are some DAO classes in project, but it have failed implementation I think.
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
In each DAO I call this method
Session mySession = HibernateUtil.getSessionFactory().openSession();
And After that doing transactions.
Now I want create generic BaseDAO class and create base CRUD operations in it. But I need get EntityManager. How can I getEntityManager in my BaseDao?
In spring I do it:
public class BaseJpaDao<E> implements BaseDao<E>{
protected Class<?> entityClass;
#PersistenceContext(unitName = "mainDataBase")
private EntityManager entityManager;
public BaseJpaDao(Class<?> entityClass) {
this.entityClass = entityClass;
}
#Override
public E persist(E e) {
entityManager.persist(e);
return e;
}
But how do it in not spring project?
Use Hibernates factory methods:
// Use persistence.xml configuration
EntityManagerFactory emf = Persistence.createEntityManagerFactory("mainDataBase")
EntityManager em = emf.createEntityManager();
// Retrieve an application managed entity manager
// Work with the EM
em.close();
Taken from the docs.
I'm using hibernate annotation in my program, but its getting error.
It returns no session factory that I opened. I used netbeans IDE and when I debug my program, it want to open a session and next step, it is going to InvocationTargetException.java and do not anything else.
it is my folders
enter image description here
it is my hibernate util
public class HibernatUtil {
private static final SessionFactory FACTORY;
static {
FACTORY = new AnnotationConfiguration().configure("/hibernate.cfg.xml").buildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return FACTORY;
}
}
it is my class that get session factory, but getting error
public class UserDAO {
private Session session;
public boolean insert(User user){
session=HibernatUtil.getSessionFactory().getCurrentSession();
Transaction transaction=null;
String result;
try{
transaction=session.beginTransaction();
session.save(user);
transaction.commit();
result="your insert was sucssedfull";
}
catch(Exception e ){
result="your transaction was faild";
if (transaction!=null) transaction.rollback();
}
System.out.println(result);
return transaction!=null ;
}
}
and then after next step go too this class
enter image description here
Try using this HibernateUtil instead :
public class HibernateUtil {
public static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// create the SessionFactory from hibernate.cfg.xml
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;
}
}
and in your userDao use this :
private final SessionFactory sessionFactory = HibernateUtil.sessionFactory.getCurrentSession();
I am using Hibernate 4.3. I am trying to get the SessionFactory object from a HibernateUtil class. I am trying to get only one SessionFactory object for entire application, i.e. Singleton object for application.
Below is my current code, I want to make it Singleton class.
HibernateUtil.java
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static StandardServiceRegistry serviceRegistry;
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
Please suggest or provide sample code for this.
Thanks.
Just apply singleton pattern
public class HibernateUtil {
private static StandardServiceRegistry serviceRegistry;
private volatile 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();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
INSTANCE = configuration.buildSessionFactory(serviceRegistry);
}
}
Edit: fixed a comma typo
Rather than making HibernateUtil as singleton.Make SessionFactory as singleton.
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory=configuration.buildSessionFactory(serviceRegistry);
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Advantages of above approach as below
1.no synchronize code(avoiding locking and unlocking for each method call)
2.no if condition
3.sessionfactory is eagly instantiation.(static block will be executeted only once in class life time)
4.application starup itself you can find errors in configuration files.
please suggest/comments on this..
thanks
As suggested I have made the HibernateUtil.java class as Singleton.
Find the below code, and please suggest / comment to confirm the correctness of code.
Here is the updated code:
public class HibernateUtil {
private static HibernateUtil instance = null;
private static SessionFactory sessionFactory;
private static StandardServiceRegistry serviceRegistry;
private HibernateUtil(){
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
public static HibernateUtil getInstance(){
if(instance == null){
instance = new HibernateUtil();
}
return instance;
}
public synchronized static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Please do correction if the code is not correct, and suggest the correct way.