Hibernate关系@ManyToMany使用@ OneToMany& @ManyToOne

时间:2018-06-05 15:44:28

标签: hibernate jpa annotations

本季度我正在为JPA和Hibernate工作。我有一个无限循环。我试图使用@ManyToMany,但老师不希望我们使用它。所以我用过它。

这是第一个实体,

@Entity
@Table(name = "Routes")
public class Routes {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name = "id_route")
private Long id;

@OneToOne
private Airport origin;

@OneToOne
private Airport destination;

@Column(name = "distance")
private float distance;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "route")
private List<RouteXCabin> cabinas= new ArrayList<>();

第二个,

@Entity
@Table(name = "Cabins")
public class Cabin {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name = "id_cabin")
private int id;

@NotBlank
@Column(name = "name")
private String nombre;

最后是加入实体/表

@Table(name = "routes_x_cabins")
public class RouteXCabin {
@Id
@GeneratedValue
@Column(name = "id_Rxc")
private Long id;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "fk_id_route")
private Routes route;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "fk_id_cabin")
private Cabin cabin;

我有这个循环Image。 知道怎么解决这个问题吗? 感谢

1 个答案:

答案 0 :(得分:0)

N

你得到无限循环,因为你为它们设置了eager fetch类型。您应该至少使用延迟提取类型设置其中一个。实际上,您可以删除提取类型,因为OneToMany的默认提取类型是惰性的,而且ManyToOne非常渴望。