Previously I was using the following code to configure the sessionFactory, but after upgrading the version of my hibernate from 4.2.1.Final to 4.3.4.Final, I can not retrieve sessionFactory using the following code as ServiceRegistryBuilder() is deprecated.
I used this link to create it but the provided function is not returning any thing therefore it runs into pre-compile error.
private static SessionFactory configureSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (HibernateException e) {
System.out.append("** Exception in SessionFactory **");
e.printStackTrace();
}
return sessionFactory;
}
static {
try {
sessionFactory = configureSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSession() throws HibernateException {
Session session = threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
sessionFactory = configureSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
if (session.isOpen()) {
session.close();
}
}
}
In 4.3, you should use the StandardServiceRegistryBuilder instead.
import org.hibernate.boot.registry.StandardServiceRegistryBuilder
StandardServiceRegistryBuilder was added as a new parent of ServiceRegistryBuilder. The rest of the code should be the same. The only place that I have found this documented "clearly" is in the 4.3 JavaDocs for ServiceRegistryBuilder.
One thing that I did not notice was that they changed the ServiceRegistryBuilder.buildServiceRegistry() method to just StandardServiceRegistryBuilder.build(). Therefore, it will require you to change that part of your building process:
new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
Becomes:
new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
I tested this one and it works on Hibernate 4.3.6
public class HUtil{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties()).build();
sessionFactory = configuration.configure(). buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return createSessionFactory();
} }
Yes, they have deprecated the previous ServiceRegistryBuilder(), here is how you can do it with Hibernate 4.3.4
public void testConnection() throws Exception {
logger.info("Trying to Connect With a DataBase.");
Configuration configuration = new Configuration();
configuration.configure("Your.cfg.xml");
ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder().applySettings(configuration
.getProperties());
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());
Session session = sessionFactory.openSession();
logger.info("Database connection created successfuly.");
}
Source: Create session factory in Hibernate 4
Related
I can't creat sessionFactory. It throws an exception. Please help me to fix it:
public class HibernateUtil<ServiceRegistryBuilder> {
private static final SessionFactory sessionFactory;
static{
try{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Session Factory could not be created." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
I have hibernate query, for example get user by id:
public User findById(int id){
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Transaction tx = null;
User user = null;
try{
tx = session.beginTransaction();
user = (User) session.get(User.class, id);
session.getTransaction().commit();
} catch(HibernateException e){
if(null != tx) tx.rollback();
System.out.println("HibernateException, transaction will be rollbacked");
} catch(Exception e){
e.printStackTrace();
}
finally {
session.close();
}
return user;
}
It's ok for one query, but i need dublicate all of this code to every query.
I need just on single code:
user = (User) session.get(User.class, id);
Is it possible to put other code to another class, method or something else?
Updated
HibernateUtil:
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
It is a good practice to keep one Hibernate utility class which will have a static method to provide us the hibernate session. Moreover you can reuse the hibernate session by preventing making a new session on each query by using some simple logic.
I am trying to configure hibernate and tomcat, so that tomcat will manage the database conections, but I am getting some errors.
Could you help? Here is my code:
Here is the HibernateUtil
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().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;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
HibernateListener:
public class HibernateListener implements ServletContextListener {
/* public void contextInitialized(ServletContextEvent event) {
HibernateUtil.getSessionFactory(); // Just call the static initializer
// of that class
}
public void contextDestroyed(ServletContextEvent event) {
HibernateUtil.getSessionFactory().close(); // Free all resources
}
}*/
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("\n\tInside contextInitialized()\n")
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
HibernateUtil.shutdown();
}
}
I have also made an entry in web.xml
<listener>
<listener-class>hibernate.HibernateListener</listener-class>
</listener>
I have created a jsp file and try to run a piece of code, which is:
public Employee getEmployeeByLogin(String login){
Employee p= null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Query query = session.createQuery("from employee p where p.login = '" + login +"'");
p = (Employee) query.uniqueResult();
return p;
}
The error I am getting is:
org.apache.jasper.JasperException: org.hibernate.HibernateException: createQuery is not valid without active transaction
I tried to do it similar way as described in https://community.jboss.org/wiki/UsingHibernateWithTomcat# but without success....
So once again. Please help.
In our application we have an HibernateSessionFactory class, that is opening and closing connections. Everything is okay, but when we are updating data in the database, it doesn't change in our application. Unfortunately, we see old data from the database. How can I fix this?
public class HibernateSessionFactory {
private static final ThreadLocal threadLocal = new ThreadLocal();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
private static final Logger log = Logger.getLogger(
HibernateSessionFactory.class);
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
log.error("Error Creating SessionFactory", e);
}
}
private HibernateSessionFactory() {}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ?
sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
log.error("Error Creating SessionFactory", e);
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.flush();
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Configuration getConfiguration() {
return configuration;
}
}
.
#SuppressWarnings("unchecked")
public List<Tauthor> getAuthors() throws HibernateException {
log.debug("getting all authors");
Query queryObject = null;
List<Tauthor> authors = null;
Session session = HibernateSessionFactory.getSession();
try {
String queryString = "from Tauthor";
queryObject = session.createQuery(queryString);
authors = queryObject.list();
} catch (HibernateException e) {
log.error("get all authors failed", e);
throw e;
} finally {
HibernateSessionFactory.closeSession();
}
return authors;
}
You haven't shared your code where you write data to the database. Without that, I can think of only a few reasons as to why your data output is old instead of new data:
Your transactions are not being committed.
Hibernate hasn't written to the database at the time of data queried by you.
Hibernate's cache hasn't been updated, which results in query returning old data.
You should verify that data has been written to the Database with a db developer tool and try disabling all hibernate caching to see if the result changes.
I am using Hibernate + jersey Rest And Mysql as backend for database. In Hibernate used cp3 pool for connection but after some time it creates so many idle connections and gets stuck. my configurations are :
package com.appname.hibernate.util;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
Configuration configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
} catch (HibernateException he) {
System.err.println("Error creating Session: " + he);
he.printStackTrace();
throw new ExceptionInInitializerError(he);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
////////////////////// INSIDE DAO ///////////////////////////
private Session getSession() {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session;
try {
session = sessionFactory.getCurrentSession();
} catch (org.hibernate.HibernateException he) {
session = sessionFactory.openSession();
}
return session;
}
public Users regsiterUser(Users users) throws Exception {
Session session = null;
try {
session = getSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(users);
transaction.commit();
return users;
//Using context session that is why I am not closing session
} catch (Exception e) { throw e; }
}
I am calling this DAO function form my controller where I am making transaction and session inside DAO layer. Please help me I am trying to solve this but not getting any solution please have a look what is wrong with the above configuration and code ......
Thanks in advance.....
I think this session = sessionFactory.openSession(); should be closed manually after use because it is not managed by an orchestrator that release resource after use.