Spring @Query annotation with enum parameter

Is it possible to use enum parameter with @Query annotation?

Here is the code that I use to find the user role:

Role userRole = roleRepository.findByRole(Roles.USER);
if ( userRole == null ) {
    LOGGER.debug("No role found with role: {}", Roles.USER);
}

and he prints

No role found with role: ROLE_USER

but if I try to find all the 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, the user role exists.

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

}

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

}
+4
source share
1 answer

I suggest using the listed JPA types . Modify a role property as follows:

@Column(name = "role")
@Enumerated(EnumType.STRING)
private Roles role;

This should automatically fix the query result.

+1
source

Source: https://habr.com/ru/post/1015738/


All Articles