我有一个基本的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次购买
答案 0 :(得分:0)
如果对具有生成ID的实体覆盖等于,则需要处理两个ID均为空的情况。否则,HashSet会将新实体视为相等,并且只会存储一个。
在这种情况下,您可以使用默认值等于
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Purchase other = (Purchase) obj;
if(this.id == null) {
if(other.id == null) {
return super.equals(other);
}
return false;
}
return this.id.equals(other.id);
}