-
FEATURED COMPONENTS
First time here? Check out the FAQ!
Hi,
I am using Hibernate with ZK HibernateUtil to persist Objects. It works good for any HttpRequests. But for my application I need to start a thread that listens on a socket for incoming messages. These messages should also persist with Hibernate.
As the persist command is not called within an HttpRequest, the OpenSessionInViewListener doesn't work and it throws an exception that there is no active transaction.
Is there a solution to handle Hibernate commands with HibernateUtil within threads?
kind regards
Ben
Samplecode:
-----------
EntityA.java:
-----------
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class EntityA {
private int _id;
public EntityA() {}
@Id
public int getId() {return _id;}
public void setId(int id) { _id = id;}
}
-------------
EntityA_DAO.java:
-------------
public class EntityA_DAO {
org.hibernate.Session _session;
public EntityA_DAO() {
_session = HibernateUtil.getSessionFactory().getCurrentSession();
}
public void saveOrUpdate(EntityA newEntityA) {
_session.saveOrUpdate(newEntityA);
}
}
--------------
TestWindow.java
--------------
import org.zkoss.zul.Window;
public class TestWindow extends Window {
private Thread t;
public TestWindow(){
t = new Thread(new UpdateRunnable());
t.start();
}
class UpdateRunnable implements Runnable{
public void run() {
while(true){
EntityA a = new EntityA();
new EntityA_DAO.saveOrUpdate(a);
}
}
}
}
since you create a thread yourself, why don't you just use you DAO in simple J2SE application way?
get the DataSource/Session/JDBC form spring/jind , open a Connection, sets the transaction, execute the sql , finally commit it and release the connection.
Do you mean 'same session' ?
I don't think it is good idea if you use same session in two different asynchronized thread.
Asked: 2008-09-11 10:48:35 +0800
Seen: 238 times
Last updated: Sep 15 '08