JPA:一个具有主键的表,另一个具有主键和外键的表 [英] JPA : one table with primary key and another table with primary and foreign key

查看:298
本文介绍了JPA:一个具有主键的表,另一个具有主键和外键的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I started studing JPA by reading a book and they gave an unidirection mapping which is like this:

车辆

table vehicle

(vehicleId, brand, model, dev_year, extraId) 

vehicleId 是PK, extraId 是FK

vehicleId is the PK, extraId is the FK

travel_extra

table travel_extra

(id, allowSmoke, allowFood, allowDrinks, airConditioner)

id 是PK

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; 

}

当我坚持 commit 交易时,它就像是一种魅力.

When i persist and commit the transaction it works like a charm.

但是!就我而言,我不希望车辆表具有外键,但我希望该外键位于 travel_extra 表中并链接至车辆的主键桌子.但是,当我这样做时,代码将无法正常工作,无论我尝试做什么,我都无法使其正常工作.

However! for my case i don't want the vehicle table to have a foreign key but i want the foreign key to be in the travel_extra table and link to the primary key of vehicle table. BUT when i do that the code doesnt work and no matter what i try to do i can not make it work.

如果有人曾经经历过这样的事情,我会很乐意为您提供一些帮助以及如何使其工作的示例.

If somebody has ever experianced such thing i will be happy for some assitance and examples of how to make it works.

谢谢.

推荐答案

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

Try with @JoinColumn(name = "vehicleId", insertable = false, updateable = false), and create a vehicleID column in TravelExtra table. insertable = false, updateable = false should instruct ORM to look for the column in target table.

编辑

我的参考是,其中指出:

My reference is this, where it states:

在JPA中,JoinColumn定义了 insertable updatable 属性,这些属性可用于指示JPA提供者外键实际上在目标对象的表中

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实体中添加映射,就不需要进一步的数据库更改)

If it doesn't work (since it is not guaranteed by the specification), you can make the relation bidirectional (just add a mapping in TravelExtra entity, no further database changes needed)

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

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

这篇关于JPA:一个具有主键的表,另一个具有主键和外键的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆