我连接了两个表并从两个表中获取不同的列以将它们加载到数据表中。我想使用 dataTable 对列进行排序,但如何了解哪些列属于哪些表?我的意思是,当我单击数据表中 last_name 列 上的排序按钮时,如何编写 order by table1_.last_name desc
因为有来自 table2 的列。
所以我的代码看起来像这样;
public Page<UserDTO> findByCriteria(String columnName, final String filters, String sort, Pageable pageable) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UserDTO> cq = cb.createQuery(UserDTO.class);
Root<UserDTO> iRoot = cq.from(UserDTO.class);
Join<UserDTO, User> bJoin= iRoot.join("user");
cq.multiselect(bJoin.get("id"), bJoin.get("login"), bJoin.get("firstName"), bJoin.get("lastName"), bJoin.get("dayOfBirth"), iRoot.get("district"));
........
if (!columnName.equals("district")) {
.....
}
.......
if (sort.split(":")[0].equals("district") || columnName.equals("district")) {
.......
}
.........
}
如您所见,我使用 !columnName.equals("district")
来区分表,但这不是通用方法。我无法对其他表使用此方法,因为它们可能使用不同的列,因此我必须一次又一次更改列名称以区分表。
我要问的是,是否有像 contains
这样的方法用于 iRoot 和 bJoin 来检查 table 是否包含那个columnName?
最佳答案
在 Criteria API 中,您应该考虑实体及其属性,而不是表和列。
因此,假设您想在(例如)UserDTO.lastName
上订购,这可能是这样的:
cq.orderBy(iRoot.get("lastName"));
What I'm asking is that, is there a method like contains for iRoot and bJoin to check if table contains that columnName ?
Root
有一个 getModel
方法,它返回一个 EntityType
,它提供实体的元数据。您可以在那里检查属性等。不完全是列名,但很接近。
关于java - 如何检查表是否包含 JPA - Criteria API 中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49346372/