![](/img/trans.png)
[英]Hibernate giving org.hibernate.NonUniqueObjectException and saving obsolete object to the database
[英]Hibernate not saving Object in the Database?
我有以下问题,当试图在数据库中插入对象时,休眠卡住,没有返回错误,对象没有正确保存。
调试它我发现它挂在
Hibernate: select nextval('hibernate_sequence')
我正在使用 PostgreSQL 作为数据库。
我的配置文件:
<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);
}
SELECT 部分有效。
我不确定我错过了什么。 也使用本机 SQL 插入命令,它可以工作。
我没看到你这么忙
Session session = sessionFactory.openSession();
session.save(mc);
session.flush();
session.close();
但最可取的是
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 让事情变得更简单:
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.