简体   繁体   English

"Hibernate 不在数据库中保存对象?"

[英]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.我正在使用 PostgreSQL 作为数据库。

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. SELECT 部分有效。

I'm not sure what I'm missing.我不确定我错过了什么。 Also using native SQL Insert command, it works.也使用本机 SQL 插入命令,它可以工作。

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: Kotlin 让事情变得更简单:

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) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM