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.
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();
}
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) }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.