【发布时间】:2019-10-03 09:07:53
【问题描述】:
我有一个基本的 SpringBoot 2.1.5.RELEASE 应用程序。使用 Spring Initializer、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR 文件。
我有这个域类:
@Entity
@Table(name="t_purchase")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Purchase implements Serializable {
public Purchase() {
}
public Purchase(Shop shop) {
super();
this.shop = shop;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonProperty("id")
private Long id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = “shop_id")
@JsonIgnore
Shop shop;
…
}
还有
@Entity
@Table(name = “t_shop")
public class Shop implements Serializable {
public Shop(String name) {
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonProperty("id")
private Long id;
@JsonProperty("name")
private String name;
@OneToMany(mappedBy = “shop", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JsonIgnore
private Set<Purchase> purchases = new HashSet<Purchase>();
…
}
以及仓库中的这个方法:
@Query("select shop from Shop shop left join shop.purchases where shop.id = ?1")
Shop shopPurchases (Long shopId);
然后我创建了这个 Junit 方法:
@Test
public void testFindByShopIdWithPurchases () {
Shop shop = new Shop ("Shop_NAME");
shopService.save(shop);
Purchase purchase1 = new Purchase(shop);
Purchase purchase2 = new Purchase(shop);
shop.getPurchases().add(purchase1);
shop.getPurchases().add(purchase2);
shopService.save(shop);
Shop shopWithPurchases = shopService.findByShopIdWithPurchases(shop.getId());
assertEquals (2, shopWithPurchases.getPurchases().size());
}
但它失败了,因为它返回 1 个购买而不是 2 个
【问题讨论】:
标签: hibernate spring-boot jpa orm spring-data-jpa