我使用spring boot,使用jpa(hibernate)和postgresql
我使用复合键。
@Entity
@IdClass(SamplingsPK.class)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Samplings {
@Id
@GeneratedValue
private Integer id;
@Id
private int year;
@OneToMany(mappedBy = "sampling", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Samples> samples = new ArrayList<>();
...
}
public class SamplingsPK implements Serializable {
private Integer id;
private int year;
public SamplingsPK(Integer id, int year) {
this.id = id;
this.year=year;
}
private SamplingsPK(){
}
@PrePersist
public void prePersist() {
year = LocalDate.now().getYear();
}
}
@Entity
public class Samples {
@Id
@SequenceGenerator(name = "samples_id_seq", sequenceName = "samples_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "samples_id_seq")
private Integer id;
private String sampleLetter;
@ManyToOne
@JoinColumns({
@JoinColumn(name = "sampling_id", referencedColumnName = "id"),
@JoinColumn(name = "sampling_year", referencedColumnName = "year")
})
private Samplings sampling;
}
工作正常
我希望有一个复合键,而不是样本中的序列...... SamplingsPK + sampleLetter。
是否可以这样做,如何保存样品?
答案 0 :(得分:1)
这是“派生身份”,因此Samples
可以使用@IdClass
映射,如下所示:
@Entity
@IdClass(SamplesPK.class)
public class Samples {
@Id
@ManyToOne
@JoinColumns({
@JoinColumn(name = "sampling_id", referencedColumnName = "id"),
@JoinColumn(name = "sampling_year", referencedColumnName = "year")
})
private Samplings sampling;
@Id
private String sampleLetter;
}
public class SamplesPK {
SamplingsPK sampling; // matches name of attribute and type of Samplings PK
String sampleLetter; // matches name and type of attribute
}
在第2.4.1节的JPA 2.2 spec中讨论派生身份(带示例)。