spring-data-jpa 一个简单的多对一关系如何既创建一个连接表,又创建一个返回父级的FK?

ioekq8ef  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(120)

非常简单的用例。实体Pet对客户是多对一:

@ManyToOne(targetEntity = Customer.class, optional = false)
    private Customer customer;

Customer实体本身具有对Pet的引用

@OneToMany(targetEntity = Pet.class)
        private List<Pet> pets;


以下是生成的实体关系图:

生成的DDL为:

create table customer (
       id bigint generated by default as identity,
        name varchar(255),
        notes varchar(255),
        phone_number varchar(255),
        primary key (id)
    )

    create table customer_pets (
       customer_id bigint not null,
        pets_id bigint not null
    )

    create table pet (
       id bigint generated by default as identity,
        birth_date date,
        name varchar(255),
        notes varchar(255),
        type integer,
        customer_id bigint not null,
        primary key (id)
    )

  alter table customer_pets 
       add constraint UK_e3o1kteg0lcbv0x7ootmqr9be unique (pets_id)

    alter table customer_pets 
       add constraint FKgg2of4dlj1tcnp4we00jnym8n 
       foreign key (pets_id) 
       references pet

    alter table customer_pets 
       add constraint FK3vxa5mji0399s17amtnv2f2qj 
       foreign key (customer_id) 
       references customer

alter table pet 
       add constraint FKt742r2fu4c3i9sn6a8kv0k746 
       foreign key (customer_id) 
       references customer

实体的完整定义为:

@Entity
@Table
@Data
@NoArgsConstructor
public class Pet implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private PetType type;

    private String name;

    @ManyToOne(targetEntity = Customer.class, optional = false)
    private Customer customer;

    private LocalDate birthDate;

    private String notes;
}

@Entity
@Table
@Data
@NoArgsConstructor
public class Customer implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;

    private String phoneNumber;

    private String notes;

    @OneToMany(targetEntity = Pet.class)
    private List<Pet> pets;

    public void insertPet(Pet pet) {
        pets.add(pet);
    }
}

为什么Hibernate会创建两个连接表 customer_pets,但同时保留一个从 Pet到Customer 的FK?
我也使用过JoinColumn,但还是一样!

deyfvvtc

deyfvvtc1#

这是因为你的Map是错误的。你必须告诉Hibernate哪个一对一的关联Map这个一对多的关联,例如,用途:

@OneToMany(mappedBy = "customer")
private List<Pet> pets;

相关问题