i have a problem with hibernate but i don't understand what is this problem exactly
if you have an idea?
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<Customer> listCustomer() {
return sessionFactory.getCurrentSession().createQuery("FROM customer").list();
}
Main.java
public class Main {
public static void main(String[] args) {
CustomerDaoImpl dao=new CustomerDaoImpl();
for(int i=0; i<dao.listCustomer().size(); i++){
System.out.println(i);
}
}
}
error
Exception in thread "main" java.lang.NullPointerException
at com.apps.dao.CustomerDaoImpl.listCustomer(CustomerDaoImpl.java:37)
at com.apps.dao.Main.main(Main.java:8)
You must initialize your sessionFactory. In earlier hibernate versions you did it like this
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Since version 4.3.0. you have to do this
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
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 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.
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();
}