JPA - 当参数是属性的成员时选择,属性是一组字符串

时间:2018-05-23 09:48:14

标签: java sql spring-data-jpa

NoticeGroupEntity

@Id
@Column(name = "id")
private long id;

@Column(name = "name")
private String name;

@Column(name = "allowed_user_statuses")
@Convert(converter = StringSetConverter.class)
private Set<String> allowedUserStatuses;

这是StringSetConverter

public class StringSetConverter implements AttributeConverter<Set<String>, String> {

@Override
public String convertToDatabaseColumn(Set<String> list) {
    return String.join(",", list);
}

@Override
public Set<String> convertToEntityAttribute(String joined) {
    return new HashSet<>(Arrays.asList(joined.split(",")));
}

我尝试使用JPA选择NoticeGroupEntity

@Query("SELECT ng FROM #{#entityName} ng WHERE ?1 IN ng.allowedUserStatuses")
List<NoticeGroupEntity> findByAllowedUserStatus(String userStatus);

有什么方法可以选择吗?它不会返回任何实体。 感谢。

1 个答案:

答案 0 :(得分:0)

你的@Query太奇怪了。

试试这个:

@Query("SELECT ng FROM NoticeGroupEntity ng WHERE ?1 member ng.allowedUserStatuses")

上述实体工作。我还没有尝试过原始类型。

如果它不起作用,原生查询将来拯救:

@Query(value = "SELECT ng FROM NoticeGroupEntity ng WHERE ng.allowed_user_statuses LIKE ?1", native = true)

并将参数传递为"%" + status + "%"