有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java映射JPA复合外键

我是JPA的新手,希望创建一个具有以下关系的数据库:

|Participant|
|id : INT (PK) | id_event : INT (PK, FK) |

|Event|
|id : INT (PK) |

我完全不知所措,几乎无法理解我找到的示例的语法:/

但我知道我需要创建另一个类来包含PK的两个部分,这就引出了另一个问题:这个类是否可以是一个内部类(出于优化目的)

我希望我没有要求太多,但我真的很想得到它


共 (1) 个答案

  1. # 1 楼答案

    你的实体可能是这样的:

    @Entity
    public class Participant {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        @OneToMany(fetch = FetchType.LAZY)    // or any other relation
        private List<Event> events;
    
        // fields, constructors, getters, setters
    }
    
    @Entity
    public class Event {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        // fields, constructors, getters, setters
    }
    

    在本例中,JPA将使用以下查询创建3个表(SQL方言会因数据库而异,在本例中,我使用了H2数据库):

    CREATE TABLE Event (
      id bigint GENERATED BY DEFAULT AS IDENTITY,
      PRIMARY KEY (id)
    );
    
    CREATE TABLE Participant (
      id bigint GENERATED BY DEFAULT AS IDENTITY,
      PRIMARY KEY (id)
    );
    
    CREATE TABLE Participant_Event (
      Participant_id bigint NOT NULL,
      events_id      bigint NOT NULL
    )
    

    Participant_Event是自动创建的联接表,用于链接参与者和事件

    下面是一个理解JPA entity relations的好例子