我正在尝试通过其ID从采购订单(Po)获取材料。路径和连接表中有一些集合。
Po.java
@Entity
@Table(name = "T_PO")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Po implements Serializable {
@ManyToOne
@JoinColumn(name = "customer_id", referencedColumnName = "id")
private Customer customer;
@OneToMany(mappedBy = "po", targetEntity = Po_part.class)
private List<Po_part> partList;
Part.java
@Entity
@Table(name = "T_PART")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Part implements Serializable {
@ManyToMany
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name = "T_PART_MATERIAL",
joinColumns = @JoinColumn(name="parts_id", referencedColumnName="ID"),
inverseJoinColumns = @JoinColumn(name="materials_id", referencedColumnName="ID"))
private Set<Material> materials = new HashSet<>();
@OneToMany(mappedBy="part",targetEntity=Po_part.class)
private List<Po_part> partList;
Po_part.java
@Entity
@Table(name = "T_PO_PART")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Po_part implements Serializable {
@ManyToOne
private Part part;
@ManyToOne
private Po po;
Material.java
@Entity
@Table(name = "T_MATERIAL")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Material implements Serializable {
@ManyToOne
@JoinColumn(name = "supplier_id", referencedColumnName = "id")
private Supplier supplier;
@ManyToOne
@JoinColumn(name = "supplier_id_2", referencedColumnName = "id")
private Supplier supplier2;
MaterialRespository中的JPA查询
@Query("SELECT m FROM Material m "
+ "JOIN Po po "
+ "JOIN po.partList po_part "
+ "JOIN po_part.part parts "
+ "JOIN parts.materials materials "
+ "WHERE po.id = ?1")
List<Material> getListOfMaterialsForPo(Long id);
最终结果是我希望能够获得Po
所需的材料列表------- UPDATE ---------
我得到了以下的Query来处理mySQL工作台,但是当我真正需要实际的Material对象来访问其getter时它才返回库存。不确定这是否可以用SQL解决。
查询:
@Query(value="SELECT materials.inventory_count materials "
+"FROM hillcresttooldie.t_po po "
+"join hillcresttooldie.t_po_part po_part "
+"on po_part.po_id = po.id "
+"join hillcresttooldie.t_part part "
+"on part.id = po_part.part_id "
+"join hillcresttooldie.T_PART_MATERIAL material "
+"on material.materials_id = part.id "
+"join hillcresttooldie.T_MATERIAL materials "
+"on material.materials_id = materials.id "
+"where po.id LIKE %?1", nativeQuery = true)
List<Integer> getListOfMaterialsForPo(Long id);
还有一件让我想知道的事情是JPA的mySQL类工作台。在Eclipse中,我有以下附加组件:
但是我从未使用过它。认为将此添加到帖子中会很有帮助。
答案 0 :(得分:1)
花些时间真正学习JPQL。这并不难。 JPQL使用关联来进行连接。您需要的查询就像
一样简单select material from Po po
join po.partList popart
join popart.part part
join part.materials material
where po.id = :poId
请为您的类提供有意义的名称,并尊重Java命名约定。