2

I'm attempting to do a little task using Hibernate and JSF .

Here's my snippet of code . managed bean method that supposed to retrieve a list of tags :

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
public  List<WikiTag> getTags(){
    session.getTransaction().begin();
    Criteria crit = session.createCriteria(WikiTag.class);
    List<WikiTag> result = crit.list();     
    return result;
}

I understand that i can't have more than one session open. However when i call that snippet of code from a facelet i get

org.hibernate.TransactionException: nested transactions not supported

Any light thrown on this is much appreciated . thanks

Rehme
  • 323
  • 3
  • 6
  • 20

2 Answers2

3

You can't have more then one transaction (not session) active at same time (I'm writing about your case).
Probably your method is already under transaction and you don't need to create a new one; remove session.getTransaction().begin();.
Look How to avoid nested transactions not supported error?

In addiction, right pseudo-code for transaction management is:

tx = begin tx;
try
{
  do database operations;
  commit tx;
  tx = null;
}
finally
{
  if(tx != null)
  {
    rollback tx;
  }
}
Community
  • 1
  • 1
Luca Basso Ricci
  • 17,829
  • 2
  • 47
  • 69
  • I only have one transaction open . when i remove that line `session.getTransaction().begin();`, i get org.hibernate.HibernateException: createCriteria is not valid without active transaction – Rehme Sep 12 '13 at 08:44
  • did you try begin/commit/rollback best pratice? Your code is non correct because you never close transaction you begun (rewrite e try again) – Luca Basso Ricci Sep 12 '13 at 08:49
  • I tried it sir. But I got a 3rd exception `org.hibernate.SessionException: Session is closed!` – Rehme Sep 12 '13 at 09:10
1

First, Accessing database in getters setters is wrong. getTags method called several times during page is rendered. You can not do transactional database connections in action methods..

Second, acceesing database in JSF action is not a good practice. You should access databases in other classes they generally called DAO classes.

See also

Database Communication in JSF/EJB

DAO tutorial - the data layer

Community
  • 1
  • 1
erencan
  • 3,725
  • 5
  • 32
  • 50