(playframework 2.0.2-java) EBean - No ScalarType registered error when querying with enum values

*爱你&永不变心* 提交于 2019-12-06 16:56:09

The quickest solution, assuming that you are mapping EnumValue exactly the same as the enum names:

public enum RoleNameEnum {
    @EnumValue("REGULAR")
    REGULAR,
    @EnumValue("ADMIN")
    ADMIN
}

Then you can implement the findByRole method as following:

public static List<User> findByRole(Role role) {
    return find.where().eq("role", role.name()).findList();
}

where the magic is just using the mapped string value instead of the enum instance for the role name.

I posted a bug on the ebean issue tracker: http://www.avaje.org/bugdetail-427.html, binder should detect the enum object and interpret it as its mapped value automatically.

EDIT:

In case that you need some other mapping than the simple enum value, here it is the utility code to get the value set using the @EnumValue annotation

public static <T extends Enum<T>> String serialize(T theEnum) {
    try {
        for (Field f : theEnum.getDeclaringClass().getDeclaredFields()) {
            if (theEnum.equals(f.get(theEnum))) {
                EnumValue enumValue = f.getAnnotation(EnumValue.class);
                if (enumValue != null)
                    return enumValue.value();
            }
        }
    } catch (Exception e) {
    }
    return null;
}

Then you can implement findByRole using the serialize method

public static List<User> findByRole(Role role) {
    return find.where().eq("role", serialize(role)).findList();
}

Looks like the issue is that you have a roles list, not a single property on your user.

@Constraints.Required
@ManyToMany
public List<Role> roles = new ArrayList<Role>();

To query against that list, try:

public static List<User> findByRole(Role role) {
    return find.where().in("roles", role).findList();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!