问题
I am using Spring Data and Repositories. I created an Entity with a enum type field, which I declared @Enumerated(EnumType.STRING), but I am forced to create a method getAuthority returning a String.
@Entity
@Configurable
public class BaseAuthority implements GrantedAuthority {
@Enumerated(EnumType.STRING)
@Column(unique = true)
private AuthorityType authority;
@Override
public String getAuthority() {
return authority.toString();
}
}
The enum is as follow:
public enum AuthorityType {
REGISTEREDUSER, ADMINISTRATOR;
}
In the repository for the entity, I created an operation to find by authority type:
@Repository
public interface BaseAuthorityRepository extends JpaRepository<BaseAuthority, Long> {
BaseAuthority findByAuthority(AuthorityType authority);
}
However, I get a warning:
Parameter type (AuthorityType) does not match domain class
property definition (String). BaseAuthorityRepository.java
I used to have the operation receiving a String rather than AuthorityType, but that generates a runtime exception. I could change the name of the field authority to authorityType, but I don't like that.
Am I doing something wrong? How can I remove the warning?
回答1:
I guess you have to rename the field, but you can do it in an transparent way:
@Entity
public class BaseAuthority implements GrantedAuthority {
private static final long serialVersionUID = 1L;
@Enumerated(EnumType.STRING)
@Column(unique = true, name = "authority")
private AuthorityType authorityType;
AuthorityType getAuthorityType() {
return authorityType;
}
@Override
public String getAuthority() {
return authorityType.toString();
}
}
and change your repository to
@Repository
public interface BaseAuthorityRepository extends JpaRepository<BaseAuthority, Long> {
BaseAuthority findByAuthorityType(AuthorityType authority);
}
来源:https://stackoverflow.com/questions/25161241/spring-data-enumeration-and-repository-issue