I would like to have multiple Hibernate transactions in a single EJB method call (running in WildFly). Currently my current_session_context_class is set to jta and transaction.factory_class is org.hibernate.transaction.JTATransactionFactory.
Now, for example, the following code fails:
public void myMethod(){
try{
Transaction tr = myHibernateSessionFactory.getCurrentSession().beginTransaction();
//execute some DB operation
tr.commit();
tr = myHibernateSessionFactory.getCurrentSession().beginTransaction();
//execute some DB operation
tr.commit();
}catch(Exception e){
e.printStackTrace();
}
}
The problem is that the second call to beginTransaction() throws an exception org.hibernate.TransactionException: Transaction instance is no longer valid.
How do I get a new transaction for the current session?
Related
I'm calling a stored procedure below, everything works fine but I have observed that (through visualizing connections on db) for some reason application does not releases the connection after executing below code and every time this code is executed, a new connection is created until the limit reaches and its not able to acquire the JDBC connection anymore.
NOTE: the em (entity manager) is autowired here:
Session session = em.unwrap(Session.class);
try{
ProcedureCall call = session.createStoredProcedureCall("sp_name");
Output outputs = call.getOutputs().getCurrent();
List<Object[]> resultList = ((ResultSetOutput) outputs).getResultList();
session.close();
return resultList;
}catch(Exception e){
session.close();
return null;
}
Below is the HikariCP configuration
spring.datasource.hikari.maximumPoolSize=10
spring.datasource.hikari.minimumIdle=2
spring.datasource.hikari.idleTimeout=15000
spring.datasource.hikari.maxLifetime=600000
spring.datasource.hikari.connectionTimeout=30000
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.
I have a service that reads data from database. After reading there is a flush which causes the exception mentioned in the title. Below is the sequence of statements
ManagerFactory factory = new ManagerFactory();
EntityManager manager = factory.getManager();
EntityTransaction transaction = manager.getTransaction();
Query query = manager.createQuery("select personRoleJPA from personRoleJPA");
personRoleJPA = (PersonRoleJPA) query.getSingleResult();
if (manager.isOpen()) {
manager.flush();
}
if (manager.isOpen()) {
manager.close();
manager = null;
}
if (transaction.isActive()) {
transaction.commit();
}
I suspect the exception is because I did not begin the transaction. My question is do you really need to flush & commit when you are not doing any writes ?
Remove everything related to transaction since you dont need an active transaction to retrieve data:
ManagerFactory factory = new ManagerFactory();
EntityManager manager = factory.getManager();
Query query = manager.createQuery("select personRoleJPA from personRoleJPA");
personRoleJPA = (PersonRoleJPA) query.getSingleResult();
if (manager.isOpen()) {
manager.flush();
}
if (manager.isOpen()) {
manager.close();
manager = null;
}
About flush() method you can read from documentation:http://docs.oracle.com/javase/1.5.0/docs/api/java/io/OutputStream.html#flush%28%29
If you read anything from database you do not need transaction.commit().commit() using for saving changes after sql statement executed but in select statement you do not need commit.Default in JDBC commit is auto-commit mode.In hibernate configuration file you can change this settings.The best practice is disabling auto-commit mode.
About commit() you can also read from:https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html
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 am using jersey with mysql and hibernate 4 and c3p0. I have created a initialization servlet that configures hibernate and sets the current session context class to thread.
I have created hibernateUtils class that contains static methods for getting and committing sessions and I am using a filter to start a session on inbound request and commit it upon response.
The problem is that at some random intervals I am getting org.hibernate.TransactionException: nested transactions not supported exception, but I am not trying to create a new session except on the filter.
Correct me if I am wrong but when setting the current session class to thread I don't need to create a threadlocal in the hibernateutil, hibernate does this. So my question is, is this a safe way to handle that and what could cause the error happening on random intervals?
====================== EDIT ===========================
Sorry for not posting the code earlier.
So the filter implements the ContainerRequestFilter,ContainerResponseFilter
in the request filter I am doing
Session session = sessionfactory.getCurrentSession();
session.getTransaction().begin();
session.setDefaultReadOnly(readOnly);
and in the response
Transaction transaction = sessionfactory.getCurrentSession().getTransaction();
try {
if (transaction != null && !transaction.wasCommitted()
&& !transaction.wasRolledBack() && transaction.isActive()) {
transaction.commit();
}
} catch (HibernateException e) {
Transaction transaction = sessionfactory.getCurrentSession().getTransaction();
try {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
} catch (HibernateException e) {
} finally {
Session session = sessionfactory.getCurrentSession();
try {
if (session != null && session.isOpen()) {
session.close();
}
} catch (HibernateException e) {
log.error("Closing session after rollback error: ", e);
throw e;
}
}
It seems that you are using programmatic transaction demarcation in your filter (as far as I understood). So please double check that you terminate properly each transaction, nevermind what append during the request (i.e. rollback if you get an exception and commit otherwise) :
try {
session.getTransaction().begin();
// call the filter chain
session.getTransaction().commit()
}
catch (RuntimeException e) {
session.getTransaction().rollback();
}
Without the code it's difficult to be sure, but I guess that for some request you didn't terminate the transaction properly (i.e. by a commit or by a rollback). So the transaction remains associated to the thread and the thread go back to the thread pool (in a very strange state since there is still a transaction associated with it), then another request reuse the same thread, a new transaction is created in the filter... and you got the exception.
EDIT
After looking carrefully at your code, it (may) confirms my assumptions.
Look at the flow when transaction.wasRolledBack()==true : it won't be commited nor rolled back.
And if you the javadoc for Transaction.wasRolledBack() :
Was this transaction rolled back or set to rollback only?
If the transaction is marked as "RollBack only" : it will return true, but it don't means that the transaction is ended. It means that the only possible ending state for the transaction is "RollBack".
But, on the other hand the same javadoc also say this:
Returns: boolean True if the transaction was rolled back via this local transaction; false otherwise.
I found that ambiguous.
So I suggest you to do this:
if (transaction != null && !transaction.wasCommitted()
&& !transaction.wasRolledBack() && transaction.isActive()) {
transaction.commit();
}else if(transaction.wasRolledBack()){
transaction.rollback();
}