gpt4 book ai didi

java - hibernate 不保存外键

转载 作者:行者123 更新时间:2023-11-30 10:15:17 24 4
gpt4 key购买 nike

在使用 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;
...
}

当我保存采样时,我会在样本表中看到

抽样编号抽样年

不是饲料

这应该是 orm 的工作吗?

在示例中,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;

结果一样

此外,如果在样本中我想使用像主键一样的采样主键+字段字母,有没有办法做到这一点?

最佳答案

这可能与尼古拉斯所说的相反

只检查这个例子

https://github.com/hibernate/hibernate-orm/blob/ceaeb81e3362ff187004ea3479b2afeeba5aa8a6/documentation/src/test/java/org/hibernate/userguide/mapping/identifier/IdClassGeneratedValueTest.java#L77

更改为 cascade.all,应该会有所帮助...可能将数据分散到合并而不是持久。

可能是 spring boot 的问题?

关于java - hibernate 不保存外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50495668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com