这是我的枚举:
public enum UserRole {
SYS_ADMIN,
CALIBRATOR_ADMIN,
PROVIDER_ADMIN,
}
实体:
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Table(name = "USER")
public class User {
@Id
private String username;
private String password;
private String firstName;
private String lastName;
@Embedded
private Address address;
@ManyToOne
@JoinColumn(name = "organizationId")
@JsonManagedReference
private Organization organization;
@ElementCollection
@JoinTable(name = "USER_ROLE", joinColumns = @JoinColumn(name = "username"))
@Enumerated(EnumType.STRING)
@Column(name = "value", length = 30)
private Set<UserRole> userRoles = new HashSet<>();
以及我如何尝试进行搜索查询:
public static CriteriaQuery<User> buildSearchQuery(String userName, String role, String firstName, String lastName, EntityManager em, String fieldToSort) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> criteriaQuery = cb.createQuery(User.class);
Root<User> root = criteriaQuery.from(User.class);
Predicate predicate = ProviderEmployeeQuary.buildPredicate(root, cb, userName,role, firstName, lastName);
if (fieldToSort.length() > 0) {
if (fieldToSort.substring(0, 1).equals("-")) {
if (fieldToSort.substring(1, fieldToSort.length()).equals("userRoles")) {
criteriaQuery.orderBy(cb.desc(root.<Set<UserRole>>get(fieldToSort.substring(1, fieldToSort.length()))));
} else {
criteriaQuery.orderBy(cb.desc(root.get(fieldToSort.substring(1, fieldToSort.length()))));
}
} else {
if (fieldToSort.equals("userRoles")) {
criteriaQuery.orderBy(cb.asc(root.<Set<UserRole>>get(fieldToSort)));
} else {
criteriaQuery.orderBy(cb.asc(root.get(fieldToSort)));
}
}
}
criteriaQuery.select(root).distinct(true);
criteriaQuery.where(predicate);
return criteriaQuery;
}
执行此代码时出错:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:你有一个 SQL语法错误;查看与您的手册相对应的手册 MySQL服务器版本的正确语法使用附近&#39; asc limit 5&#39;在 第1行
生成的JPQL查询:
从User选择distinct generatedAlias0作为generatedAlias0 inner 将generatedAlias0.organization加入generateAlias1其中( generatedAlias1.id = 11L)和(1 = 1)order by generatedAlias0.userRoles desc