[英]how to get data or query from Many to Many?
我有產品和代碼實體,並為他們建立了ManyToMany關系,所以它將成為Product_Code
因此Product_Code將具有product_id和product_id
我真的很想通過代碼從產品中獲取數據,但是我想要的結果我也想從產品值和代碼值中獲取詳細信息,我不知道如何在JPA上做到這一點
我在想先獲取產品代碼,然后在Product_Code表上找到該id的id產品,然后從中獲取數據並再次在代碼實體上找到代碼的id,我確信有辦法為此獲取數據,但我不知道如何,而且我確實希望獲得一種簡單的方法來了解其工作原理
我在這里很新
我的實體產品是這樣的
@Entity
@Table(name = "PRODUCT")
@Setter
@Getter
@DynamicUpdate
public class Product extends Base {
@ManyToMany(mappedBy = "products", fetch = FetchType.EAGER)
private Set<Code> codes;
@Column(name = "NAME", nullable = false)
private String Name;
@Column(name = "DESCRIPTION")
private String description;
public int hasCode() {
return Objects.hashCode(getId());
}
}
這是我的代碼實體:
@Entity
@Table(name = "CODE")
@DynamicUpdate
@Setter
@Getter
public class Voucher extends Base {
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "PRODUCT_CODE",
joinColumns = @JoinColumn(name = "CODE_ID"),
inverseJoinColumns = @JoinColumn(name = "PRODUCT_ID"))
private Set<Product> products;
@Column(name = "CODE", unique = true)
private String codeName;
@Column(name = "TYPE", nullable = false)
private String type;
private String descriptions;
public int hasCode() {
return Objects.hashCode(getId());
}
}
我真的想獲取所有數據,當我嘗試通過代碼查找時,請說我想查找具有“ A7”之類代碼的產品,因此我想從產品實體中獲取信息,然后我還將獲取詳細代碼實體與product_id和code_id相似的產品
當我嘗試使用Product findByCode(String code)
或Product findOneByCode(String code)
,結果是我擴展的Base
實體,而不是Product實體, Base
實體是可重用的實體,如generate id, token, createdAt, deletedAt, updatedAt
這可以通過啟用JpaSpecificationExecutor<Product>
存儲庫上的Specification<Product>
來實現。
ProductRepository
實現JpaSpecifiactionExecutor<Product>
然后,在您的@Service
注入VoucherRepository
和ProductRepository
某個位置執行以下操作:
//implement a method in VoucherRepository findByName which returns Voucher instance.
Voucher code = voucherRepository.findByName("A7");
//then pass the instance to isMember function in ProductRepository
List<Product> products = productRepository.findAll((r, q, b) -> b.isMember(code, Product_.codes));
評論
r, q, b
是用於lambda表達式的方法參數,例如對Specification<Product>
重寫方法toPredicate
。 如果您的項目限制您使用Java 7及以下版本,則可以使用以下方法實現此對象:
Specification<Product> spec = new Specification<Product>() {
@Override
public Predicate toPredicate(Root<Product> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
return criteriaBuilder.isMember(code, root.get(Product_.codes));
}
};
參量
r
表示根元素Root<Product>
q
代表條件查詢CriteriaQuery<?>
b
代表條件構建器CriteriaBuilder
Product_.*
是您的Product
實體的靜態元模型。 它可以使用JPA模型生成器自動生成,也可以使用@Staticmetamodel
注釋手動創建。
通過執行findAll(Specification<Product>)
您可以進行類似於過濾的選擇,其中結果列表將僅包含符合條件的產品。
編輯:
您的Product
元模型可能看起來像(現在),但是,我建議使用元模型生成器。
@StaticMetamodel(Product.class)
public class Product_ {
public static volatile SetAttribute<Product, Code> codes;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.