我目前正在开发一个java ee应用程序,但我遇到了JPA的问题。 我有两个实体:
@Entitiy
public class Restaurant implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Desk> desks;
}
@Entitiy
public class Desk implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "restaurant_id")
private Restaurant restaurant;
}
我正在使用以下代码存储办公桌:
Desk desk = new Desk();
desk.setNumber(Integer.toString(x));
desk.setRestaurant(restaurant);
em.persist(desk);
但现在奇怪的是,实体餐厅的办公桌清单是空的,但实体服务台的餐厅价值是正确的。 数据库shema看起来像这样:
RESTAURANT (ID)
DESK (ID, RESTAURANT_ID)
RESTAURANT_DESK (RESTAURANT_ID, DESK_ID)
表RESTAURANT_DESK始终为空。为什么生成第三个表?为什么实体餐厅的办公桌清单是空的?
答案 0 :(得分:1)
对于双向映射,您需要在mappedBy
实体中提供Restaurant
属性以指示反向关系:
@Entity
public class Restaurant implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="restaurant")
private List<Desk> desks;
}
答案 1 :(得分:0)
我发现了问题。我不得不将实体台也添加到餐馆列表中。
Desk desk = new Desk();
desk.setNumber(Integer.toString(x));
desk.setRestaurant(restaurant);
restaurant.getDesks().add(desk);
em.persist(desk);