'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.



Solution 1:[1]

Kotlin makes things easier:

import org.hibernate.Session

val session: Session get() = sessionFactory.openSession()

fun Session.executeTransaction(action: (Session) -> Unit) = use {
    val transaction = it.beginTransaction()
    action(it)
    transaction.commit()
}

fun <T> T.saveToDb() = session.executeTransaction { it.save(this) }

fun <T> T.updateAtDb() = session.executeTransaction { it.update(this) }

fun <T> T.deleteFromDb() = session.executeTransaction { it.delete(this) }

Usage example:

class UserService {

    fun save(user: UserEntity) {
        user.saveToDb()
    }
}

or

val user = UserEntity(id = 1, name = "John Snow")
user.saveToDb()

Maybe someone will need also:

import org.hibernate.SessionFactory
import org.hibernate.boot.registry.StandardServiceRegistryBuilder
import org.hibernate.cfg.Configuration

object HibernateSessionFactoryUtil {

    val sessionFactory: SessionFactory by lazy {
        val configuration = Configuration().configure()
        configuration.addAnnotatedClass(UserEntity::class.java)
        val builder = StandardServiceRegistryBuilder().applySettings(configuration.properties)
        configuration.buildSessionFactory(builder.build())
    }
}

We are using Kotlin .use{} which automatically closes the session in finally block

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Space