jpa规范不起作用

e4yzc0pl  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(363)

我正在实现一个基于两个实体的搜索。

  1. @Entity(name = "user")
  2. public class UserEntity {
  3. @Id
  4. @GeneratedValue(generator = "system-uuid")
  5. @GenericGenerator(name = "system-uuid", strategy = "uuid")
  6. @Column(updatable = false, nullable = false)
  7. private String id;
  8. @Column(unique = true, nullable = false)
  9. private String email;
  10. @OneToOne(cascade = CascadeType.ALL)
  11. @JoinColumn(name = "foo_id", referencedColumnName = "id")
  12. private FooEntity foo;
  13. private UserType type;
  14. }
  15. @Entity(name = "foo")
  16. public class FooEntity {
  17. @Id
  18. @GeneratedValue(generator="system-uuid")
  19. @GenericGenerator(name="system-uuid", strategy = "uuid")
  20. @Column(updatable = false, nullable = false)
  21. private String id;
  22. private String identifier;
  23. }

现在,我想根据email adres查找用户,或者根据关系中的标识符查找footentity关系是否存在。并基于userentity中的枚举类型。
我尝试了以下查询:

  1. public static Specification<UserEntity> emailLike(String text) {
  2. return (root, query, criteriaBuilder) -> criteriaBuilder.like(root.get("email"), "%" + text + "%");
  3. }
  4. public static Specification<UserEntity> patientIdentifier(String text) {
  5. return (root, query, criteriaBuilder) -> criteriaBuilder.like(root.join("foo").get("identifier"), "%" + text + "%");
  6. }
  7. public static Specification<UserEntity> userType(UserType type) {
  8. return (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("type"), type);
  9. }
  10. final Specification<UserEntity> specification = Specification.where(
  11. UserSpecification.patientIdentifier(text)
  12. .or(UserSpecification.emailLike(text))
  13. ).and(
  14. UserSpecification.userType(type)
  15. );
  16. final Page<UserEntity> userEntities = userRepository.findAll(specification, pageable);

现在,当与footentity的关系存在时,这个查询似乎可以工作。当此关系为null时,即使电子邮件和类型匹配,也不会返回任何内容。
有人能帮我吗?

ve7v8dk2

ve7v8dk21#

你不应该只是加入,而是左加入或右加入。联接是内部联接,这意味着它只匹配符合联接条件的记录。在sql中,任何等于null的值都是false,所以我认为连接站点中的任何一个都是null,记录不在结果集中。因此,左连接表示,用所有左站点实体进行响应,并仅在右站点存在时匹配右站点,如果不存在,则右站点为null。
所以join应该看起来像 root.join("foo", JoinType.LEFT) (未测试)

相关问题