在一个带有hibernate和jpa的spring boot 2项目中,
我尝试保存一些对象
@Embeddable
public class EmbedddedSamplesKey implements Serializable {
private Integer id;
private int year;
...
}
@Entity
@IdClass(EmbedddedSamplesKey.class)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Samplings {
@Id
@GeneratedValue
private Integer id;
@Id
private int year;
@OneToMany(mappedBy = "sampling", cascade = CascadeType.PERSIST, orphanRemoval = true)
private List<Samples> samples = new ArrayList<>();
public void addSample(Samples sample) {
samples.add(sample);
sample.setSampling(this);
}
public void removeSample(Samples sample) {
samples.remove(sample);
sample.setSampling(null);
}
...
}
@Entity
public class Samples extends BaseEntity {
@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 letter;
//@OneToOne(optional = false, cascade = CascadeType.PERSIST)
//private TestSamples testSamples;
@ManyToOne
private Samplings sampling;
...
}
当我保存采样时,我会在样本表中看到
sampling_id sampling_year
不是Feed
这应该是这样做的工作吗?
在样本中,orm生成了这个
ALTER TABLE samples
ADD CONSTRAINT fkq5if151jgtlcy7yfp55ffvf47 FOREIGN KEY (sampling_id, sampling_year)
REFERENCES samplings (id, year)
ON UPDATE NO ACTION
ON DELETE NO ACTION;
编辑,尝试
@ManyToOne
@JoinColumns({
@JoinColumn(name = "sampling_id", referencedColumnName = "id"),
@JoinColumn(name = "sampling_year", referencedColumnName = "year")})
private Samplings sampling;
但结果相同
另外,如果在样本中我想使用像主键那样的采样主+字段字母有没有办法做到这一点?
答案 0 :(得分:1)
它可能与尼古拉斯所说的相反
请查看此示例
更改为cascade.all,应该有帮助...可能会将数据sprind到合并而不是持久化。
可能是春季启动问题?
答案 1 :(得分:0)
也许不是最好的答案,但最好等3个月才能得到答案....时间就是金钱
如果不知道需要在序列上做任何特殊操作....
只需使用序列,添加一个瞬态字段,该字段将是序列+年....
答案 2 :(得分:0)
粗略地看一眼,我认为你不能将@GeneratedValue与@IdClass一起使用。
Auto Increment not working for Entity class with composite Key