gpt4 book ai didi

java - 带有枚举参数的 Spring @Query 注解

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:55:58 25 4
gpt4 key购买 nike

是否可以使用带@Query 注解的枚举参数?

这是我用来查找用户角色的代码:

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

但如果我试图找到所有角色,这就是我得到的:

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]

如您所见,用户角色确实存在。

角色库:

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();
}

}

最佳答案

尝试在 Query 中使用 SpEl 并像这样调用 Enum 参数的 toString():

@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);

关于java - 带有枚举参数的 Spring @Query 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17242408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com