我想问一下如何将 exampleMatcher 用于具有 List 属性的类。假设,我们有一个用户可以同时拥有多个角色。我想从数据库中获取所有具有用户角色的用户
实体
@Entity(name = "UserEntity")
public class User {
Private Long id;
private String name;
private String surname;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn
private Address address;
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
@JoinColumn
private List<UserRole> roles;
}
@Entity
public class UserRole {
private Long id;
private String name;
}
我将带有一些属性的用户类发送到 getExampleEntity。我现在正在尝试从 UI 发送所选角色的列表。
Controller 中的函数
@Override
protected User getExampleEntity() {
User clonedUser = new User();
List<UserRole> selectedRole = new ArrayList<>();
// this cycle just find and add all roles in db based on selection from UI
for (Long roleID : selectedUserRoleIDs)
selectedRole.add(userRoleService.find(roleID));
clonedUser.setRoles(selectedRole);
return clonedUser;
}
来自 JpaRepository 的函数,它使用示例匹配器调用 findByExample 函数。
@Override
public List<TObjectType> findByExample(int first, int pageSize, String sortField, Sort.Direction sortOrder, TObjectType type)
{
PageRequest pageRequest = getPageRequest(first, pageSize, sortField, sortOrder);
ExampleMatcher exampleMatcher = getExampleMatcher();
Example<TObjectType> example = Example.of(type, exampleMatcher);
return repository.findAll(example, pageRequest).getContent();
}
/**
* Generates an example matcher for the instance of {@link TObjectType}.
* This can be overriden if a custom matcher is needed! The default property matcher ignores the "id" path and ignores null values.
* @return
*/
protected ExampleMatcher getExampleMatcher() {
return ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreNullValues();
}
如果将发送具有属性名称/姓氏或什至地址类中的任何属性的用户,它就像一个梦想,但它不适用于列表角色。 对于如何解决此问题以及如何将 findByExample 与 TObjectType 数组用作属性的任何提示,我将不胜感激。 非常感谢
编辑: 我发现了问题。有一个repository.findAll函数的代码(org.springframework.data.repository.query.QueryByExampleExecutor#findAll)
@Override
public <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) {
ExampleSpecification<S> spec = new ExampleSpecification<S>(example);
Class<S> probeType = example.getProbeType();
TypedQuery<S> query = getQuery(new ExampleSpecification<S>(example), probeType, pageable);
return pageable == null ? new PageImpl<S>(query.getResultList()) : readPage(query, probeType, pageable, spec);
}
生成的查询不包含列表属性,但我不知道为什么它包含在 Example 对象中。有人遇到过这个问题吗?我猜只有一些设置/注释问题。
最佳答案
你应该首先尝试使用transformer。下面的示例适用于 Mongodb,但您可以看到方法。在我的例子中,用户类包含字符串形式的角色列表:
final ExampleMatcher matcher = ExampleMatcher.matching()
.withIgnoreNullValues()
.withMatcher("roles", match -> match.transform(source -> ((BasicDBList) source).iterator().next()).caseSensitive());
users = userRepository.findAll(Example.of(criteria, matcher), pageRequest);
关于java - 如何将 spring 数据示例匹配器用于列表属性 - 查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42026166/