【发布时间】:2014-11-14 17:11:52
【问题描述】:
我在使用 Hibernate 和 Postgres 时遇到问题。我正在重复代码块以进行测试,以确保一切正常。但是,此代码块包含重复持久化方法以将两个用户帐户持久化到 useraccount 表。它第一次正常工作。但是,以后每次我运行代码时,UserAccount 对象的 ID 都会递增,而表中对应的用户保持其原始值。我尝试使用 native 和 identity 作为生成器类,identity 将 id 保持在 0 和 native 具有我上面描述的相同问题。
我意识到这是一个不切实际的情况(通过相同的代码块重复),但我不认为这是应有的表现。事实上,在从所有表中删除所有条目后,用户就会正确地添加到用户表中。有没有办法确保他的对象属性id与表id同步?
这是用户帐户 ID 的 xml 映射。
<class name="UserAccount" table="useraccounts">
<id name = "UserId" type="int" column="user_id" unsaved-value="null">
<generator class="increment"/>
</id>
这里是 Hibernate 配置文件
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.PostgreSQL82Dialect
</property>
<property name="hibernate.connection.driver_class">
org.postgresql.Driver
</property>
<property name="hibernate.connection.url">
jdbc:postgresql://localhost:5432/agora-db
</property>
<property name="hibernate.connection.username">
postgres
</property>
<property name="hibernate.connection.password">
postgres
</property>
<property name="connection_pool_size">1</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
【问题讨论】:
-
注意:使用 postgres 超级用户登录应用程序通常不是一个好主意。最好为他们创建一个特殊的角色。
-
有道理。我仅将其用于调试目的。谢谢!
标签: java hibernate postgresql orm identifier