2

I was trying to write my first Hibernate project. But I got an exception.

java.lang.ClassCastException: org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction cannot be cast to hibernate.HibernateSession

This is how I code session methods.

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class HibernateSession {

    static Connection.NewHibernateUtil hibernateutil;
    static SessionFactory sessionfactory;
    static Session session;
    static Transaction transaction;

    private HibernateSession() {
    }

    public static HibernateSession getHSConnection() {
        if (transaction == null) {
            session = Connection.NewHibernateUtil.getSessionFactory().openSession();
            transaction = session.beginTransaction();
        }
        return (HibernateSession) transaction;
    }

    public static void closeHSConnection() {
        if (transaction != null) {
            session.flush();
            transaction.commit();
        }
        session.close();
    }
}

Are there any errors in this code?

RubioRic
  • 2,442
  • 4
  • 28
  • 35
Poorna Senani Gamage
  • 1,246
  • 2
  • 19
  • 30

2 Answers2

3

You can't cast an object to your class when it is an instance of a completely different class (JDBCTransaction)

  return (HibernateSession) transaction; // this is the error
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
1

In this answer Joakim's explanation is perfect.

You have a couple of options depending on what you really want.

  • If you need HibernateSession object (an object from the class which you have written), change the return statement of getHSConnection() to,

    return new HibernateSession();
    
  • Or if you need the newly created org.hibernate.Transaction then change your method

    public static Transaction getHSConnection() {
        ...
        return transaction;
    }
    

But I suggest that you should return neither of those. Return the org.hibernate.Session. Because,

  1. I don't see any instance variables in your class HibernateSession so there's no point of returning an object of a class with static variables and methods, in fact that should be the reason why your have a private constructor for that class.

  2. You can always get the current transaction using the method beginTransaction(). the javadoc says,

    ...If a new underlying transaction is required, begin the transaction. Otherwise continue the new work in the context of the existing underlying transaction...

So I suggest you change your method like this,

public static Session getHSConnection() {
    ...
    return session;
}

and when you need to commit the transaction,

Session s = HibernateSession.getHSConnection();
s.beginTransaction().commit();

Remember it all depends on your requirement.

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80