我使用Spring框架。 我有两个表包装和项目以及关系是一个包有多个项目。 该表的设计是这样的:
包
@Entity
@Table(name = "TB_PACKAGE")
public class Packages implements Serializable{
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(name = "PACKAGE_ID")
private String packageId;
@Valid
@OneToMany(mappedBy = "packages", cascade = { CascadeType.ALL })
private List<Item> item;
项目
@Entity
@Table(name = "TB_ITEM")
public class Item implements Serializable{
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(name = "ITEM_ID")
private String itemId;
@ManyToOne
@JoinColumn(name="PACKAGE_ID")
private Packages packages;
@Transient
private String packageId;
样本记录
这是我怎么写我的代码使用CriteriaBuilder得到结果像这样连接表。
SQL:
SELECT * FROM Packages p JOIN Item i ON p.packageId = i.packageId;
Java的:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Packages> cq = cb.createQuery(Packages.class);
Root<Packages> pRoot = cq.from(Packages.class);
Join<Packages, Item> packagesItem = pRoot.join("item");
List<Predicate> predicates = new ArrayList<Predicate>();
if (StringUtils.isNotEmpty(itemName)) {
predicates.add(cb.like(cb.lower(packagesItem.<String>get("itemName")), "%" + itemName.toLowerCase() + "%"));
}
Predicate[] predArray = new Predicate[predicates.size()];
predicates.toArray(predArray);
cq.where(predArray);
cq.distinct(true);
TypedQuery<Packages> query = em.createQuery(cq);
return query.getResultList();
如果我输入“手机”作为我的参数,它想应该拿出一个记录作为JSON:
"packageId": "P1",
"item": [
{
"itemId": "Item 1",
"temName" "Phone"
}
]
然而,包始终与它的所有子像这样加载:
"packageId": "P1",
"item": [
{
"itemId": "Item 1",
"temName" "Phone"
},
{
"itemId": "Item 2",
"temName" "Laptop"
},
{
"itemId": "Item 3",
"temName" "Mouse"
}
]
我已经尝试了一切:FetchType.Lazy,QueryDsl,原生查询,HQL等,但仍然没有运气。 任何人有解决办法吗?