Spring Data:枚举和存储库问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25161241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Data: Enumeration and Repository issue
提问by Manu
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.
我正在使用 Spring 数据和存储库。我创建了一个带有枚举类型字段的实体,我将其声明为@Enumerated(EnumType.STRING),但我被迫创建了一个返回字符串的方法 getAuthority。
@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.
我曾经让操作接收字符串而不是 AuthorityType,但这会生成运行时异常。我可以将字段权限的名称更改为 authorityType,但我不喜欢那样。
Am I doing something wrong? How can I remove the warning?
难道我做错了什么?我怎样才能消除警告?
回答by Christof R
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);
}

