我有这三个豆子:
User.java
@Entity
@Table(name = "usuario")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Set<Role> roles = new HashSet<Role>(0);
private String login;
private String password;
private Integer id;
private DestinationGroup destinationGroup;
....
// Getters and setters
DestinationGroup.java
@Entity
@Table (name = "grupo_destinatario")
public class DestinationGroup implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Integer id;
private Set<User> users = new HashSet<User>();
....
// Getters and setters
Role.java
@Entity
@Table (name = "perfil")
public class Role extends AbstractModel implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Integer id;
....
// Getters and setters
我想让所有没有角色“admin”的用户按其destinationGroup的名称排序。所以我使用这段代码:
UserTest.java
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<User> criteriaQuery = criteriaBuilder.createQuery(User.class);
Root<User> root = criteriaQuery.from(User.class);
Join<User, Role> path = root.join("roles", JoinType.LEFT);
Expression<Object> filter = path.get("name");
Predicate localPredicate = criteriaBuilder.notEqual(filter, "admin");
criteriaQuery.where(localPredicate);
Join<User, DestinationGroup> path2 = root.join("destinationGroup", JoinType.LEFT);
Expression<Object> sort = path2.get("name");
List<Order> orders = new ArrayList<Order>();
orders.add(criteriaBuilder.asc(sort));
criteriaQuery.orderBy(orders);
TypedQuery<User> query = entityManager.createQuery(criteriaQuery);
List<User> users = query.getResultList();
但如果任何用户有多个角色,那么会返回重复的结果。所以我在测试代码的第二行添加:“。distinct(true)”来只检索每个用户的一个结果:
CriteriaQuery<User> criteriaQuery = criteriaBuilder.createQuery(User.class).distinct(true);
然后抛出异常:“对于SELECT DISTINCT,ORDER BY表达式必须出现在选择列表中”。我无法删除orderBy,我想避免重复的结果。我怎么解决这个问题?我可以添加不同的关系吗?
我尝试了this solutio n但是使用JoinType.INNER我也得到了重复的结果。