带有枚举参数的Spring @Query批注 [英] Spring @Query annotation with enum parameter
本文介绍了带有枚举参数的Spring @Query批注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将枚举参数与@Query注释一起使用?
Is it possible to use enum parameter with @Query annotation?
这是我用来查找用户角色的代码:
Here is the code I'm using to find user role:
Role userRole = roleRepository.findByRole(Roles.USER);
if ( userRole == null ) {
LOGGER.debug("No role found with role: {}", Roles.USER);
}
它会打印出来
No role found with role: ROLE_USER
但是,如果我尝试查找所有角色,这就是我得到的:
but if I try to find all roles this is what I get:
for ( Role r : roleRepository.findAll() )
LOGGER.debug("{}", r);
Role@8a8c0a[roleId=1,role=role_admin,version=0]
Role@1efe9ee[roleId=2,role=role_staff,version=0]
Role@1e70f68[roleId=3,role=role_user,version=0]
Role@a475d1[roleId=4,role=role_guest,version=0]
如您所见,用户角色确实存在.
As you can see user role does exists.
RoleRepository:
RoleRepository:
public interface RoleRepository extends JpaRepository<Role, Long> {
@Query("SELECT r FROM Role r WHERE LOWER(r.role) = LOWER(:role)")
public Role findByRole(@Param("role") Roles role);
}
角色:
@Entity
@Table(name = "role")
public class Role {
public enum Roles {
ADMIN("ROLE_ADMIN"),
STAFF("ROLE_STAFF"),
USER("ROLE_USER"),
GUEST("ROLE_GUEST");
private String role;
private Roles(String role) {
this.role = role;
}
public String getRole() {
return role;
}
@Override
public String toString() {
return role;
}
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "role_id", updatable = false)
private Long roleId;
@Column(name = "role")
private String role;
@Version
@Column(name = "version")
private long version = 0;
public Long getRoleId() {
return roleId;
}
public String getRole() {
return role;
}
public long getVersion() {
return version;
}
@Override
public String toString() {
return new ReflectionToStringBuilder(this).toString();
}
}
推荐答案
尝试在查询中使用SpEl并调用Enum参数的toString(),如下所示:
Try using SpEl in Query and call toString() of Enum parameter like this:
@Query("SELECT r FROM Role r WHERE LOWER(r.role) = LOWER(:#{#role?.toString()})")
public Role findByRole(@Param("role") Roles role);
或更短:
@Query("SELECT r FROM Role r WHERE LOWER(r.role) = LOWER(:#{#role})")
public Role findByRole(@Param("role") Roles role);
这篇关于带有枚举参数的Spring @Query批注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文