JPA仅获取一级关联

时间:2018-09-15 09:25:02

标签: java hibernate spring-boot spring-data-jpa one-to-many

尝试获取应用程序中存储的所有“折扣”对象时遇到问题。 “折扣”是由以下类表示的对象

@Entity
@NoArgsConstructor
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "store")
public class Discount {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

// some fields like a description or a percentage providing info about a discount

@ManyToOne
@JoinColumn(name = "id_store")
private Store store;

@ManyToOne
@JoinColumn(name = "id_brand")
@JsonManagedReference
private Brand brand;

// getters, setters, equals and hashcode overriden below

如您所见,Discount对象可以属于商店或品牌。我确保使用触发器在代码和数据库中都只设置一个字段。在我的应用程序中,折扣既可以由品牌提供(因此我不必为此品牌的每个商店都创建折扣),也可以由特定商店提供自己的折扣。我的班级商店看起来像这样

@Entity
@NoArgsConstructor
public class Store extends Entite {

@OneToMany(mappedBy = "store", cascade = CascadeType.ALL)
private Set<Discount> discounts;

@ManyToOne
@JoinColumn(name = "id_brand", nullable = false)
private Brand brand;

// getters, setters, equals and hashcode overriden below

如您所见,商店有一组折扣,并且属于一个品牌。它扩展了Entite类,因为在我的应用中我也有Sport Clubs,并且它们共享一些信息,但这与我的问题无关。 最后,这是品牌类

@Entity
@NoArgsConstructor
public class Brand {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToMany(mappedBy = "brand", cascade = CascadeType.ALL)
private Set<Store> stores;

@OneToMany(mappedBy = "brand", cascade = CascadeType.ALL)
@JsonBackReference
private Set<Discount> discounts;

// getters, setters, equals and hashcode overriden below

“我的品牌”类别具有一组商店和一组折扣。

我的问题是我无法通过扩展interface DiscountRepository的{​​{1}}来通过简单的FindAll获取所有折扣,因为某些折扣是在关联中检索的。我从FindAll方法获得的答案如下

JpaRepository<Discount, Long>

这里的问题是有一个Store的Discount Fetch,因此,该Discount不在方法返回的原始列表中,而是在与Discount相关的Store对象中。我试图将[ { // discount fields such as percentage, ruling, etc "store": { "id": 75, "name": "Nike Store", "discounts": [ 75 ], "brand": { "name": "Nike", "store": [ 75 ] } }, "brand": null }, { // discount fields such as percentage, ruling, etc "store": null, "brand": { "name": "Uniqlo", "stores": [ 90 ] } }, { // discount fields such as percentage, ruling, etc "store": null, "brand": { "name": "FNAC", "stores": [ { "id": 76, // some store fields // problem here because Discount are retrieved here and therefore not displayed in the list, only here "discounts": [ { // discount fields such as percentage, ruling, etc // for an offer that isn't present in the original list returned // by the find all method but only here, associated to this Store object "store": 76, "brand": null } ], "brand": { "name": "FNAC", "stores": [ 76 ] } } ] } }, 76 ] 添加到我的“商店和折扣”关联中,但这不能解决问题。因此,有没有办法获取“仅一个级别的关联”?我的意思是,我只想检索我的Discount对象,而只检索Brand和Store信息,而不检索Store或Brand及其所有关联(如Set of Discount)。我希望我很清楚,不要犹豫,问我任何问题。

0 个答案:

没有答案