java - 将列表存储在表列中

标签 java spring hibernate jpa

我有表的表现和时间。一场演出可以在特定时间进行多次。一对多关系。

@Entity
@Table(name = "performance_type")
@Data
public class PerformanceType {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer performanceTypeId;
    @Column(length=127)
    private String performOptions;
}

@Entity
@Table(name = "performance")
@Data
public class Performance {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer performanceId;

    @OneToMany(mappedBy = "performance")
    private List<Hours> performanceHours = new ArrayList<>();
}

在数据库 hibernate 中创建表 hours,其 PerformanceId 只有一个值。我如何插入同时播放 id 1,4,7 的表演的列表值。我需要额外的表hours_performance来存储hourId和perfomanceId吗?

最佳答案

由于您想要实现的关系是(根据我的理解)多对多,因此您确实需要第三个表将时间映射到关系。 Here is a very good example.您需要设置第三个表,并使用两个外键连接到要连接的两个表。

@Entity
@Table(name = "performance")
@Data
public class Performance {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer performanceId;

    @ManyToMany
    @JoinTable(
        name = "hours_performance", 
        joinColumns = { @JoinColumn(name = "performance_id") }, 
        inverseJoinColumns = { @JoinColumn(name = "hour_id") }
    )
    private List<Hours> performanceHours = new ArrayList<>();
}

@Entity
@Table(name = "hours")
@Data
public class Hours {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer hourId;
    ZonedDateTime time;

    @ManyToMany(mappedBy = "performanceHours")
    private List<Performance> performances;
}

关于java - 将列表存储在表列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50666220/

相关文章:

hibernate - 更新单行的简单 PL/pgsql 存储过程中的死锁(由 Hibernate 调用)

java - 请批评我通过提供客户状态的验证进行数据导入的方法

hibernate - 多个 JPA 持久性单元指向同一个数据库?

java - 如何通过java sdk在ec2实例中第二次添加用户数据

java - web.xml、beans.xml、applicationContext.xml等的区别

java - 如何为Spring Integration提供转换器?

java - Spring Security getPrincipal() 方法返回 anonymousUser

hibernate - 初始化惰性实体的标准 JPA 方法

java - 使用 "this::content"或 "::content"包含来自同一 thymeleaf 模板的片段未按预期工作

java - java中的socket通信