java - Hibernate无法保存继承的对象

标签 java hibernate inheritance

我有两个实体 - 父类(super class)及其子类:

父类(super class)(但不是抽象):

@Entity
@Table(name="table1")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class table1 implements Serializable {
   @Id
   String id;
}

子类:

@Entity
@Table(name="table2")
public class table2 extends table1 {
   String somefield;
}

这两个表在启动期间都创建得很好。

但是当我尝试保存子类的对象时:

table2 obj = new table2();
dbSession.save(obj);

我收到错误:org.hibernate.NonUniqueObjectException:具有相同标识符值的不同对象已与 session 关联

如何解决这个问题?我只需要从第一个类扩展第二个类并将其用作不同的表。

我也尝试了.merge()方法,但仍然不起作用。

最佳答案

你有字符串id,你确定它不为空或者在你持久化对象时不存在于你的数据库中吗?

试试这个:

table2 obj = new table2();
obj.setId("new unique id")
dbSession.save(obj);

关于java - Hibernate无法保存继承的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23082520/

相关文章:

Spring Boot .JAR 无法运行(maven、intellij、hibernate...)

java - 骡子 ESB : xml to maps transformer produces empty hashmaps

java - 如何在 EmbeddedId 中强制执行 @Enumerated(EnumType.STRING)

java - 替代创建 String 对象的新方法?

java - Hibernate-Search @IndexedEmbedded with HashMap,如何在索引中包含键集

python - 如何在Python中根据子类类型定义基类参数?

html - line-height属性可以继承父div的height属性还是access所属div的height属性?

delphi - Delphi中的继承: Does each of Delphi Subclasses have its own unique copy of the Superclass Private Fields?

java - 拆箱时如何检查泛型方法的返回类型以防止 NPE

java - 扫描仪不读取整个句子 - 扫描仪类的 next() 和 nextLine() 之间的区别