Spring Data JPA (Postgres) - Insert into One table,从包含静态数据的 table 中读取外键

Spring Data JPA (Postgres) - Insert into One table, reading the foreign key from a table that contains static data

我目前正在使用 Spring Data JPA,特别是 Postgres。我们的数据库是高度规范化的。在某些情况下,我们有一些 table 包含静态数据。在那种情况下,如果我要插入 table address 并且 table address_type 包含静态数据,我需要插入 [=56 的主键=] address_type 在 table address 的列中,使外键引用从 table address 到 table address_type (静态数据)。

示例:

数据库代码

create table address_type(
    id Serial Primary Key,
    type char(3),
    description (100)
);
insert into address_type(id, type, description) values(1, 'PRIMARY', 'Primary description');
insert into address_type(id, type, description) values(2, 'SECONDARY', 'Secondary description');

关系 (1 - N)

create table address(
   id Serial Primary Key,
   address varchar(50) not null,
   address_type_id integer references address_type(id)
);
insert into address(id, address, address_type) values(1, 'address somewhere 1', 1);
insert into address(id, address, address_type) values(2, 'address somewhere 2', 1);
insert into address(id, address, address_type) values(3, 'address somewhere 3', 2);

Spring数据JPA代码

@Table(name = "address_type")
public class AddressType {
   
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @Column(name = "type")
   private String type;

   @Column(name = "description")
   private String description;

   @OneToMany(mappedBy = "addressType")
   private Address address;

   // Getters and Setters (Lombok)
}
@Table(name = "address")
public class Address {
   
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @Column(name = "type")
   private String address;

   @Column(name = "address_type_id")
   @JoinColumn(---> logic?????????? <-----)
   @ManyToOne(---> logic?????????? <-----)
   private AddressType addressType;

   // Getters and Setters (Lombok)
}

我想我的问题是我应该如何在 Address 实体的 @JoinColumn@ManyToOne 注释中设置逻辑?

P.D. 插入应该只发生在 table address, Spring 数据应该只从 table address_type 获取外键存储在address table.

经过大量研究我得到了答案 try/error。

注解里面的配置如下:

在class地址

    @Column(name = "address_type_id")
    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "address_type_id", referencedColumnName = "id")
    private AddressType addressType;

然后在 AddressType 中,您应该始终通过引用映射到 child table。

   @OneToMany(mappedBy = "addressType")
   private Address address;

需要记住的 重要 一点是,在保存回数据库之前,您应该在数据库中获取要在 child 中引用的实体table,以便 Spring Data JPA 认识到这不是 AddressType table 中的新记录,而只是一个引用并将外键保存在地址 table 中。