我遇到了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'表。
提前致谢。
答案 0 :(得分:0)
当然,您不能在不造成问题的情况下命名课程Entity
。
通过最小化注释并让JPA完成它,可以使这更简单。 Container
类包含AbstractTypes
:
@Entity
public class Container {
@Id @GeneratedValue
private Long id;
@OneToMany(cascade=CascadeType.ALL)
private List<AbstractType> types;
public List<AbstractType> getTypes() { return types; }
public void setTypes(List<AbstractType> types) { this.types = types; }
}
AbstractType
只是:
@Entity
public abstract class AbstractType {
@Id @GeneratedValue
private Long id;
}
从抽象超类扩展和继承的几个具体类型:
编辑:可以使用ManyToOne关联添加返回Container
类的FK。
@Entity
public class TypeA extends AbstractType {
@ManyToOne
private Container container;
}
和
@Entity
public class TypeB extends AbstractType {
@ManyToOne
private Container container;
}
当我运行此Minimal, Complete, Verifiable Example时,我得到以下输出:
Hibernate: create table AbstractType (DTYPE varchar(31) not null, id bigint not null, container_id bigint, primary key (id))
Hibernate: create table Container (id bigint not null, primary key (id))
Hibernate: create table Container_AbstractType (Container_id bigint not null, types_id bigint not null)
Hibernate: insert into Container (id) values (?)
Hibernate: insert into AbstractType (container_id, DTYPE, id) values (?, 'TypeA', ?)
Hibernate: insert into AbstractType (container_id, DTYPE, id) values (?, 'TypeB', ?)
Hibernate: insert into Container_AbstractType (Container_id, types_id) values (?, ?)
Hibernate: insert into Container_AbstractType (Container_id, types_id) values (?, ?)
Hibernate: select container0_.id as id1_1_ from Container container0_
model.Container@40591559