【发布时间】:2016-03-14 22:13:38
【问题描述】:
我在使用 JPA 时遇到问题。基本上,我拥有的是一个具有抽象类型列表的实体,我需要将列表中的每个元素都保存在具有外键(与实体相关)的相应表中。代码如下:
@Entity(name = "entity")
public class Entity{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private BigInteger id;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name="entity_id", referencedColumnName="id")
private List<AbstractType> types;
}
抽象类型:
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractType{
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private BigInteger id;
private String someProp;
@Column(name="entity_id")
private BigInteger entityId;
}
A型:
@Entity(name = "type_a")
@Transactional
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class TypeA extends AbstractType{
private String prop1;
private String prop2;
}
B型:
@Entity(name = "type_b")
@Transactional
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class TypeB extends AbstractType{
private String prop3;
private String prop4;
}
我遇到了 SQL 错误。生成的查询尝试更新抽象类型的表(不应该存在)。这是查询的一部分:
update hibernate_sequences set sequence_next_hi_value = ? where
sequence_next_hi_value = ? and sequence_name = 'abstract_type'
insert into type_a (some_prop, entity_id, prop1, prop2) values (?, ?, ?, ?)
insert into type_b (some_prop, entity_id, prop3, prop4) values (?, ?, ?, ?)
update abstract_type set entity_id=? where id=?
如您所见,它正在尝试更新一个不存在(也不应该)存在的表。 'abstract_type' 表。
提前致谢。
【问题讨论】:
-
如果某些东西是抽象的,使用@MappedSuperclass 更有意义。继承在根类中指定一次。不需要在子类中重新指定!
-
@Dherik,也许是同样的问题,但该解决方案对我不起作用。这种方法不会将 FK 保存在具体类的表中。
-
@NeilStockton,我知道我应该使用 MappedSuperclass,但这不起作用。那是因为我的列表是那个抽象类型的,它试图找到抽象类型实体,如果你使用那个注释它就不存在了。
-
您的意思是“它在 Hibernate 中不起作用”?在其他 JPA 实现中也是如此。
标签: java hibernate jpa one-to-many