Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate not saving Object in the Database?

I have the following problem, when trying to insert an object in the database Hibernate gets stuck, no error returned, the object is not saved correctly.

Debugging it I found out that it hangs at

Hibernate: select nextval('hibernate_sequence')

I am using PostgreSQL as a database.

My configuration file:

<hibernate-mapping>
    <class name="src.MyClass" table="MyClass">

    <cache usage="read-write"/>

    <id name="id" column="classid">
        <generator class="native" />
    </id>

    <property name="name" column="name" not-null="true" unique="true" length="160"/>

</class>
</hibernate-mapping>

@Override
public void save( Myclass mc)
{
    Session session = sessionFactory.getCurrentSession();

    session.save( mc);
}

The SELECT part works.

I'm not sure what I'm missing. Also using native SQL Insert command, it works.

like image 335
Mythul Avatar asked Aug 02 '13 15:08

Mythul


People also ask

How does Hibernate connect to database?

It represents the classname of a custom ConnectionProvider which provides JDBC connections to Hibernate. It is used to set the JDBC transaction isolation level. It enables auto-commit for JDBC pooled connections.

What is the difference between the Save () and saveOrUpdate () method of Hibernate?

Difference between save and saveOrUpdate in Hibernate The main difference between save and saveOrUpdate method is that save() generates a new identifier and INSERT record into the database while saveOrUpdate can either INSERT or UPDATE based upon the existence of a record.

What is difference between save and merge in Hibernate?

Once save/update is done, the object DOES NOT reflect the change. The returned object reflects the changes, and it is attached to hibernate session. MERGE method offers greater flexibility when it comes to saving data objects, since you need not worry about attaching object to Session.


1 Answers

I did'nt see you that flushing your session

Session session = sessionFactory.openSession();
session.save(mc);
session.flush();
session.close();

But most preferable is

Session session = factory.openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        session.save(mc);
        tx.commit(); // Flush happens automatically
    }
    catch (RuntimeException e) {
        tx.rollback();
        throw e; // or display error message
    }
    finally {
        session.close();
    }
like image 194
Suresh Atta Avatar answered Oct 01 '22 01:10

Suresh Atta