gpt4 book ai didi

java - JPA : one table with primary key and another table with primary and foreign key

转载 作者:行者123 更新时间:2023-12-01 12:10:18 29 4
gpt4 key购买 nike

我通过阅读一本书开始学习 JPA,他们给出了一个单向映射,如下所示:

表格车辆

(vehicleId, brand, model, dev_year, extraId) 

vehicleId is the PK, extraId is the FK

表格travel_extra

(id、allowSmoke、allowFood、allowDrinks、空调)

id is the PK

然后是java对象:

public class Vehicle {

@Id
private long vehicleId;
private String brand;
private String model;

@OneToOne
@JoinColumn(name = "vehicleId")
private TravelExtra travelExtra;
}


public class TravelExtra {

@Id
private id;

private boolean allowSmoke;
private boolean allowFood;
private boolean allowDrinks;
private boolean airConditioner;

}

当我坚持提交交易时,它就像一个魅力。

但是!对于我的情况,我不希望 vehicle 表有外键,但我希望外键位于 travel_extra 表中并链接到车辆的主键 table 。但是当我这样做时,代码不起作用,无论我尝试做什么,我都无法使其工作。

如果有人曾经经历过这样的事情,我将很乐意提供一些帮助和如何使其发挥作用的示例。

提前致谢。

最佳答案

尝试使用 @JoinColumn(name = "vehicleId", insertable = false, updateable = false),并在 TravelExtra 中创建一个 vehicleID 列> 表。 insertable = false, updateable = false 应指示 ORM 在目标表中查找列。

编辑

我的引用号是this ,其中指出:

In JPA the JoinColumn defines an insertable and updatable attribute, these can be used to instruct the JPA provider that the foreign key is actually in the target object's table

如果它不起作用(因为它不受规范保证),您可以使关系成为双向(只需在 TravelExtra 实体中添加映射,无需进一步更改数据库)

public class Vehicle {
...
@OneToOne(mappedBy = "vehicle", cascade = CascadeType.ALL)
private TravelExtra travelExtra;
...
}

public class TravelExtra {
...
@OneToOne
@JoinColumn(name = "vehicleId")
private Vehicle vehicle;
...
}

关于java - JPA : one table with primary key and another table with primary and foreign key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27316792/

29 4 0