SQLNonTransientConnectionException: No operations allowed after connection closed - java

I keep waking up the morning to my site being down because of this No operations allowed after connection closed.
here is the getSession method we use :
public static Session getSession() throws HibernateException {
Session session = THREAD_LOCAL.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
THREAD_LOCAL.set(session);
}
return session;
}
Here is the closeSession
public static void closeSession() throws HibernateException {
Session session = (Session) THREAD_LOCAL.get();
THREAD_LOCAL.set(null);
if (session != null) {
if (session.isOpen()) {
session.close();
}
}
}
here is the configureSessionFactory
private static SessionFactory configureSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (HibernateException e) {
e.printStackTrace();
}
return sessionFactory;
}
Here is one of our Dao function
public Client getClientInformation(int client_id) {
final Session session = HibernateUtil.getSession();
Client client = null;
try {
session.beginTransaction();
Query q = session.createQuery("FROM Client c WHERE c.id = :client_id")
.setInteger("client_id", client_id);
if (q.list().size() > 0) {
client = (Client) q.uniqueResult();
}
if (session.isOpen()) {
session.close();
}
} catch (HibernateException e) {
} finally {
HibernateUtil.closeSession();
}
return client;
}

Related

Hibernate Junit H2 In memory database test case changing fields in the development db

I have developed a project using Hibernate. I am trying to test it using Junit with H2 in memory db but the test case is creating fields in the db that I am using it for development.
Here is my code :
UserDAO.java
public interface UserDAO {
public void addUser(String username, String password);
public List<String> getUsers();
}
UserDAOImpl.java
public class UserDAOImpl implements UserDAO {
public static final Logger LOG = LoggerFactory.getLogger(UserDAOImpl.class);
private static Session session;
private static void beginSession() {
session = DbUtils.getSessionFactory().openSession();
session.beginTransaction();
}
#Override
public void addUser(String username, String password) {
String encryptedPassword = Utils.encrypt(password);
User user = new User(username, encryptedPassword);
beginSession();
try {
session.save(user);
System.out.println(user.getPassword());
session.getTransaction().commit();
} catch (SQLGrammarException e) {
session.getTransaction().rollback();
LOG.error("Cannot save user", e);
} finally {
session.close();
}
}
#Override
public List<String> getUsers() {
beginSession();
List<String> results = new ArrayList<String>();
String hql = "select username from User";
Query query = null;
try {
query = session.createQuery(hql);
results = query.list();
} catch (HibernateException e) {
LOG.error("Cannot execute query", e);
}
return results;
}
}
Files for test cases
SessionFactoryRule.java
public class SessionFactoryRule implements MethodRule {
private SessionFactory sessionFactory;
private Transaction transaction;
private Session session;
#Override
public Statement apply(final Statement statement, FrameworkMethod method, Object test) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
sessionFactory = createSessionFactory();
createSession();
beginTransaction();
try {
statement.evaluate();
} finally {
shutdown();
}
}
};
}
private void shutdown() {
try {
try {
try {
transaction.rollback();
} catch (Exception ex) {
ex.printStackTrace();
}
session.close();
} catch (Exception ex) {
ex.printStackTrace();
}
sessionFactory.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private SessionFactory createSessionFactory() {
Configuration configuration = new Configuration().configure();
configuration.addAnnotatedClass(User.class)
.addAnnotatedClass(Message.class);
configuration.setProperty("hibernate.dialect",
"org.hibernate.dialect.H2Dialect");
configuration.setProperty("hibernate.connection.driver_class",
"org.h2.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:h2:./data/db");
configuration.setProperty("hibernate.hbm2ddl.auto", "create");
SessionFactory sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
public Session createSession() {
session = sessionFactory.openSession();
return session;
}
public void commit() {
transaction.commit();
}
public void beginTransaction() {
transaction = session.beginTransaction();
}
public Session getSession() {
return session;
}`
Here is my test case
UserDAOTest.java
public class UserDAOTest {
#Rule
public final SessionFactoryRule sf = new SessionFactoryRule();
#Test
public void testAddUser() {
Session session = sf.getSession();
UserDAOImpl userDAOImpl = new UserDAOImpl();
String username = "stackoverflow";
String password = "testing";
userDAOImpl.addUser(username, password);
}
}
This test case is updating the fields username and password in the db that I am using while development. How can I stop it and use h2 in-memory db for testing.
You have session = DbUtils.getSessionFactory().openSession() in the UserDAOImpl. This is the reason of using a development database. Your SessionFactoryRule is not used at all.
So what you can to do.
The best choice is use to Spring for Hibernate configuration and unit testing.
Other option is to set sessionFactory to the UserDAOImpl using constructor.
Also, using static here is a really very very bad idea
private static Session session;

Mocking Hibernate Session

I was trying to mock hibernate session. This is the code snippet I tried:
#Before
public void setUp() {
campaignModel = DraftTestHelper.buildDraftModel();
if(sessionFactory != null) {
System.out.println("Session Factory not null");
}
else
System.out.println("Session Factory is null");
session = sessionFactory.getCurrentSession();
if(session != null) {
System.out.print("Not null");
}
else
System.out.println("Null");
}
Mock Code:
#Mock
SessionFactory sessionFactory;
#InjectMocks
DraftCampaignModelBuilder draftBuilder;
private DraftCampaignModel campaignModel;
private Session session;
According to console, session factory is not null. But hibernate session is null. Can anyone please help on this?
Thanks
I think you need to write this in your #Before method:
when(sessionFactory.getCurrentSession()).thenReturn(hibernateSession);
e.g.
#Mock
private HibernateSession hibernateSession;
#Before
public void setUp() {
when(sessionFactory.getCurrentSession()).thenReturn(hibernateSession);
campaignModel = DraftTestHelper.buildDraftModel();
if(sessionFactory == null) {
System.out.println("Session Factory is null");
}
else {
System.out.println("Session Factory is not null");
session = sessionFactory.getCurrentSession();
if(session != null) {
System.out.print("Session is not null");
}
else {
System.out.println("Session is null");
}
}
}

Proper use of session(hibernate)

Sorry for my english. I learn JavaEE and i dont know proper or not i use session in hibernate. How to use them? I use pattern DAO and hibernate. Tell my how property use session
this is HibernateUtil class
private static final SessionFactory sessionFactory;
static {
try{
sessionFactory = new Configuration().configure("/app/web/landingpage/HibernateConnect/hibernate.cfg.xml").buildSessionFactory();
}catch(Throwable ex) {
System.out.println("Error " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void close(Session session) {
if (session != null) {
try {
session.close();
} catch (HibernateException ignored) {
System.out.print("Couldn't close Session" + ignored);
}
}
}
And that class makes all operation db CategoryDaoImpl
public class CategoryDaoImpl implements CategoryDao{
private Session session = null;
//get all category
public Collection getAllCategory() {
List categoris = new ArrayList<Category>();
try{
session = HibernateUtil.getSessionFactory().openSession();
categoris = session.createCriteria(Category.class).list();
}catch(Exception e) {
System.out.println("getAllCategory "+ e);
}finally{
if(session != null && session.isOpen())
session.close();
}
return categoris;
}
//get category id
public Category getCategory(int id) {
Category cat = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
cat = (Category) session.load(Category.class, id);
}catch(Exception e) {
System.out.println("getAllCategory "+ e);
}finally{
if(session != null && session.isOpen())
session.close();
}
return cat;
}
//and below few methods that use it the some way session
}
and this servlet take results indexuser
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try{
Collection allcategory = Factory.getInstance().getCatDAO().getAllCategory();
request.setAttribute("allcategory", allcategory);
request.getRequestDispatcher("/index.jsp").forward(request, response);
} catch(Exception e) {
System.out.println(e);
} finally{
if(session!=null && session.isOpen())
session.close();
}
The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.
The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.
Basically session is used to get physical connection with database. So while you performing any DB Operations it will first open Session using sessionFactory and then Session do physical connection with database and then perform your operation and after performing operation you can close it.
Session is light weight.

How to retrieve sessionFactory from Hibernate 4.3.4.Final?

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

HibernateSessionFactory class doesn't change data from database

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.

Categories