Spring Data: Enumeration and Repository issue

允我心安 提交于 2020-02-21 11:00:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!