有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javajpa组合键部分连接

我有一个现有的数据库模式,当PK是多个字段的组合,而另一个实体中只有一个字段是FK时,我尝试在JPA中建立一对多关系:

DemandId:包含两个字段的PK类

@Embeddable
public class DemandId implements Serializable {

@Column(name = "\"ORDER\"", nullable = false)
private String order;

@Column(name = "SNRP", nullable = false)
private String number;
}

需求属性:实体本身

@Entity
@Table(name = "DEMAND")
public class DemandEntity implements Serializable {

@EmbeddedId
private DemandId id;

@OneToMany(fetch = EAGER, cascade = ALL, mappedBy = "demand")
private Set<PartEntity> parts = new HashSet<>();
}

分开

@Entity
@Table(name = "PART")
public class PartEntity implements Serializable {

@Column(name = "SNRP")
private String number;

@ManyToOne
@JoinColumn(name = "SNRP", referencedColumnName = "SNRP", insertable = false, updatable = false)
private DemandEntity demand;
}

这种方法会导致一个例外:

Exception Description: The @JoinColumns on the annotated element [field demand] from the entity class [class PartEntity] is incomplete. When the source entity class uses a composite primary key, a @JoinColumn must be specified for each join column using the @JoinColumns. Both the name and the referencedColumnName elements must be specified in each such @JoinColumn.

不幸的是,我无法添加另一个联接列

@JoinColumn(name = "\"ORDER\"", referencedColumnName = "\"ORDER\"", insertable = false, updatable = false)

因为零件表不包含ORDER字段,并且无法更改数据库的结构

有没有办法执行这种映射

问候


共 (1) 个答案

  1. # 1 楼答案

    If you have composite primary keys and you want to have one to many mapping, I would suggest rather than keeping those keys as composite primary keys, make them composite unique keys.

    并生成一个自动生成的序列作为主键

    它更好更方便。顺便说一下,这是我的个人意见

    我甚至不知道,如果这是可能的或不可能的,你正试图这样做