I have a doubt, using getCurrentSession of a sessionFactory, it generates many connections to the database.
P6Spy logs
when it reaches about 400 the application crashes:
Crash
A typical method of a query by hibernate:
#Autowired
#Qualifier(value = "sessionFactory")
private SessionFactory sessionFactory;
try {
Session s = this.sessionFactory.getCurrentSession();
Query query = s.createQuery("from x where c.numFactura = :numFactura");
query.setParameter("numFactura", numFactura);
return query.uniqueResult();
} catch (Exception ex) {
throw ex;
}
I really don't know, if these events are connected, what do you think?
the problem wasn't there, I had a problem with the Jasper Reports DB Conection, fixed by autoclosing conection on timeout.
Related
Googled a lot but didn't get any proper solution. I am trying to make a simple e-commerce website where I have to show a list of orders in admin panel but got stuck there. Error says 'Session is closed!' but I have opened a session at the begging of method. Please someone tell me what I am doing wrong.
public List<OrderModel> getAllOrders() throws HibernateException {
session = sessionFactory.openSession();
try {
final String hql = "FROM OrderModel WHERE status=:status";
Query query = session.createQuery(hql);
query.setParameter("status", "0");
return query.list();
} catch (HibernateException e) {
throw new HibernateException(e.getMessage());
} finally {
if(session.isOpen()){
session.close();
}
}
}
Session is declared in parent class.
#Autowired
protected SessionFactory sessionFactory;
protected Session session;
protected Transaction trans;
Try to replace this if(session.isOpen()) with if(session == null || session.isOpen() == false)
Copying from the comment:-
Your session object is a class variable, which is not thread safe. Perhaps some other thread is closing the session? Try putting session inside the method like
Session session = sessionFactory.openSession();
Also have a look at DAO pattern.
In Java Hibernate, when we need to do something with DB we need:
1. Open session
2. Begin transaction
3. Finish transaction
4. Close session
For example if I want to get Student list:
public static List<Student> getStudentList()
{
List<Student> l = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
String hql = "from Student";
Query query = session.createQuery(hql);
l = query.list();
} catch (HibernateException ex) {
//Log the exception
System.err.println(ex);
} finally {
session.close();
}
return l;
}
Insert a student
public static boolean addStudent(Student s)
{
Session session = HibernateUtil.getSessionFactory().openSession();
if (... /* check if student is already exists*/)
{
return false;
}
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(s);
transaction.commit();
} catch (HibernateException ex) {
//Log the exception
transaction.rollback();
System.err.println(ex);
} finally {
session.close();
}
return true;
}
Why there is no transaction in getStudentList()? Thank in advance
This hibernate article explains the behavior of SELECT operations which are not explicitly executed within a transaction.
The following example is given in the article but it's also true for your query example.
Session session = sessionFactory.openSession();
session.get(Item.class, 123l);
session.close();
A new Session is opened. It doesn’t obtain a database connection at this point.
The call to get() triggers an SQL SELECT. The Session now obtains a JDBC Connection from the connection pool. Hibernate, by default, immediately turns off the autocommit mode on this connection with setAutoCommit(false). This effectively starts a JDBC transaction!
The SELECT is executed inside this JDBC transaction. The Session is closed, and the connection is returned to the pool and released by Hibernate — Hibernate calls close() on the JDBC Connection. What happens to the uncommitted transaction?
The answer to that question is, “It depends!” The JDBC specification doesn’t say anything about pending transactions when close() is called on a connection. What happens depends on how the vendors implement the specification. With Oracle JDBC drivers, for example, the call to close() commits the transaction! Most other JDBC vendors take the same route and roll back any pending transaction when the JDBC Connection object is closed and the resource is returned to the pool.
Obviously, this won’t be a problem for the SELECT [...]
Lets extend the above example to provoke a possible problem.
Session session = sessionFactory.openSession();
Item item = session.get(Item.class, 123l);
item.setPrice(10);
session.close();
Now it depends on the JDBC driver if the new price for the Item is persisted or not.
So you can neglect begin and commit transactions on pure SELECT operations even when your JDBC driver will rollback the transaction as long as you have no database changes.
But anyway I would strongly recommend using transactions on any operation to avoid misunderstanding and problems.
My EntityManager is persisting/committing data to a Postgres database no problem. However, the connections it makes get stuck at 'Idle in transaction'. Here's my code:
public User create(User user) {
if(logger.isDebugEnabled()) {
logger.info("creating user: {}", user);
}
EntityManager entityManager = DbUtil.factory.createEntityManager();
try {
entityManager.getTransaction().begin();
// Persist takes an entity instance, adds it to the context and makes that instance managed (ie future updates
// to the entity will be tracked).
entityManager.persist(user);
entityManager.getTransaction().commit();
}
catch(RuntimeException e) {
throw getDbException(e);
}
finally {
entityManager.close();
}
return user;
}
Any idea why they aren't closing?
You say that persisting works, probably you see your data in db. But do you see all the data, weren't there failures? Your code doesn't handle transaction rollbacks, that might be the reason you see connection in 'Idle in transaction' state.
If an exception is thrown by throw getDbException(e), the transaction is not rolled back.
My question is about hibernate, actually I'm working on a Java EE application using hibernate and mysq.
Everything looks fine. but I still have one problem when I insert data via phpMyAdmin to my database, I cannot access them immediately via hibernate unless I started the server (tomcat) again.
This is because your transaction in phpMyAdmin was not committed.
Try running this query in phpMyAdmin before running commands.
SET ##AUTOCOMMIT = 1;
Or running commit; at the end of your query.
Possible duplicate of:
COMMIT not working in phpmyadmin (MySQL)
I noticed that i've forgot to add transaction.commit(); for every hibernate session.get(); method, so somehow it keeps data in the cache.
public List<User> getAllUsers(User user) throws Exception {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Criteria c = session.createCriteria(User.class).add(Restrictions.ne("idUser", user.getIdUser()));
List<User> users = c.list();
tx.commit();//i forget to add this
return users;
} catch (Exception e) {
if (tx != null) tx.rollback(); throw e;
} finally {
session.close();
}
}
I tried to test if SessionFactory was valid through:
assertFalse(sessionFactory.isClosed());
But my test passes even if the underlaying datasource could not get connections:
java.sql.SQLException: Connections could not be acquired from the underlying database!
How can I test if the SessionFactory is valid?
Seems like you really want to test whether you have valid database connectivity. SessionFactory is just a wrapper, once configured it will work as long as underlying DataSource is fine.
So how do you test DataSource? First of all various connection pools allow you to define so-called test query. Typically "SELECT 1". If your database connection pool does not expose such a functionality, just pick any connection from your pool and run similar query.
See also
How does Spring-JPA EntityManager handle "broken" connections?
How to get jdbc connection from hibernate session?
This is what my test code looks like after #Tomasz Nurkievicz answer:
#Test(description = "Test we can get the connection factory")
public void getApplicationSessionFactory() {
SessionFactory sessionFactory = null;
Session session = null;
try {
sessionFactory = createSessionFactory();
session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
assertFalse(connection.isClosed());
}
});
} finally {
if ( session != null ) {
session.close();
}
if (sessionFactory != null) {
sessionFactory.close();
}
}
}