一个用户可以扮演许多角色。我想从参数列表中获取至少具有一个角色的所有用户。
数据定义如下所示:
@Entity
public class User implements Serializable {
@Id
@Column(name = "Id",
nullable = false)
private long id;
@Column(name = "LoginName",
length = 30,
unique = true,
nullable = false)
private String loginName;
@ElementCollection
@Enumerated(EnumType.STRING)
@CollectionTable(name = "Role",
joinColumns = @JoinColumn(name = "Id"),
uniqueConstraints = @UniqueConstraint(columnNames = {"Id", "Role"}))
@Column(name = "Role")
private Set<RoleType> roles = new HashSet<RoleType>();
}
public enum RoleType {
GUEST,
ACCOUNTING,
ADMIN,
OPERATOR;
}
现在我希望所有在参数列表中至少具有一个角色的用户。该列表可以是动态的。我尝试了以下代码:
String sql = "SELECT DISTINCT u FROM User u JOIN u.roles AS r WHERE r IN :filteredRoles";
Query query = entityManager.createQuery(sql);
List<RoleType> filteredRoles = new ArrayList<RoleType>();
filteredRoles.add(RoleType.ADMIN);
filteredRoles.add(RoleType.ACCOUNTING);
query.setParameter("filteredRoles", filteredRoles);
List<User> result = (List<User>) query.getResultList();
并收到以下异常:
Exception [EclipseLink-6078] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.QueryException
Exception Description: The class of the argument for the object comparison is incorrect.
Expression: [null]
Mapping: [org.eclipse.persistence.mappings.DirectCollectionMapping[roles]]
Argument: [[ADMIN, ACCOUNTING]]
Query: ReadAllQuery(referenceClass=User sql="SELECT DISTINCT t0.Id FROM User t0, Role t1 WHERE ((t1.Role IN ?) AND (t1.Id = t0.Id))")
我尝试了 JPQL 的几种变体,但没有成功。我希望收到有用的提示。