gpt4 book ai didi

java - 通过 JPA 注释的聚合关系

转载 作者:行者123 更新时间:2023-11-29 08:43:23 24 4
gpt4 key购买 nike

我试图通过 JPA 注解在两个 Java 类之间建立聚合关系,以便将它们持久化到数据库中。

enter image description here

public class Ticket 
{
private String ticketNo;
private Date releasedDate;
private boolean printed;
}

public class Discount
{
private String percentage;
private Date releasedDate;
private boolean printed;
}

如提到here ,聚合关系是单向的,因此只需要映射一侧。来自这个 page 给出的解决方案,我认为解决方案将是:

 public class Discount 
{
private String percentage;
private Date releasedDate;
private boolean printed;
@ManyToOne(name="TICKET_ID")
private Ticket ticket;
}

然而,在一些examples of aggregation ,多边类出现在单边类里面。因此,我也在考虑这个:

 public class Ticket 
{
private String ticketNo;
private Date releasedDate;
private boolean printed;
@OneToMany(mappedBy="ticket")
private List<Discount> discounts = new ArrayList<Discount>();
}

哪个选项是正确的?

最佳答案

这是映射单向多对一关系的方式:

@Entity
public class Ticket {
@Id
@GeneratedValue
private Long id;

private String ticketNo;
private Date releasedDate;
private boolean printed;

// getters and setters
}

@Entity
public class Discount {
@Id
@GeneratedValue
private Long id;

private String percentage;
private Date releasedDate;
private boolean printed;

@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "TICKET_ID") // you can rename the join column
private Ticket ticket;

// getters and setters
}

注意:

  • JoinColumn(数据库术语中的外键)必须位于关系的多边(在您的情况下是折扣)。
  • @Id 注释也是强制性的。在这种情况下,ID 将由持久性提供程序自动生成。如果您正在使用数据库序列或表或其他一些策略,您可以重新定义它。

关于java - 通过 JPA 注释的聚合关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38311717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com