我试图获取用户的所有资产,但它只有几张桌子,而且我在编写CriteriaBuilder时遇到了麻烦。
@Entity
public class Asset {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "company_branch_id")
private CompanyBranch companyBranch;
}
@Entity
public class CompanyBranch {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "company_id")
private Company company;
@OneToMany(mappedBy = "companyBranch")
private Set<Asset> assets;
}
@Entity
public class Company {
@Id
private Long id;
@ManyToMany(mappedBy = "companies")
private Set<User> users;
@OneToMany(mappedBy = "company")
private Set<CompanyBranch> companyBranches;
}
@Entity
public class User {
@Id
private Long id;
@ManyToMany
@JoinTable(
schema = "User",
name = "user_company",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "company_id", referencedColumnName = "id")})
private Set<Company> companies;
}
我希望能够创建一个类似于SQL语句外观的CriteriaBuilder:
SELECT a.* FROM asset a
INNER JOIN company_branch b ON a.company_branch_id = b.id
INNER JOIN company c ON b.company_id = c.id
INNER JOIN user_company d ON c.id = d.company_id
WHERE d.user_id = ?
编写CriteriaBuilder代码以获取正确结果的正确方法是什么?
到目前为止,这是我的代码,但它似乎无法正常工作:
Root<Asset> assetRoot = query.from(Asset.class);
Join<Asset, CompanyBranch> companyBranchJoin = assetRoot.join("companyBranch", JoinType.INNER);
Join<CompanyBranch, Company> companyJoin = assetRoot.join("company", JoinType.INNER);
Join<Company, User> userJoin = assetRoot.join("users", JoinType.INNER);
Predicate predicate = criteriaBuilder.equal(userJoin.get("UserId"), userId);
query.where(predicate);