从列表中搜索@ElementCollection中的实体

时间:2018-09-22 14:55:15

标签: sql spring hibernate jpa jpql

我搜索了很多地方,但没有找到问题的答案,因此我将描述我的问题。 我有一个包含不同对象的用户类。内部对象具有一个后续元素列表,例如@ElementCollection。我确实搜索各个领域的用户,到目前为止,我已经对其进行了管理。但是,当我想从数据库的用户列表中的列表中找到至少一个元素时,遇到了一个问题。但是,以下代码有效,因为我不想搜索此字段(数据库中有多个用户没有此字段),因此它找不到数据库中的所有用户,而仅找到那些具有此字段集的用户

我的用户类别:

public class User {
    ...
    @OneToOne
    @Cascade(org.hibernate.annotations.CascadeType.MERGE)
    private AppearanceAndCharacter appearanceAndCharacter;
    ...
}

AppearanceAndCharacter类:

public class AppearanceAndCharacter {
    ...
    @JoinTable(name = "looking_for")
    private Set<LookingFor> lookingFor;
    ...
}

我的Jpa查询:

public interface UserRepository extends JpaRepository<User, Long> {
     ...

     @Query(value = "select u from User u, in(u.appearanceAndCharacter.lookingFor) lf where (u.sex = :sex or :sex is null) and (u.dateOfBirth <= :ageFrom or :ageFrom is null)" +
        "and (u.dateOfBirth >= :ageTo or :ageTo is null) and (u.maritalStatus in (:maritalStatus) or coalesce(:maritalStatus, null) is null)" +
        "and (u.appearanceAndCharacter.figure in (:figure) or coalesce(:figure, null) is null ) " +
        "and (u.appearanceAndCharacter.height > :heightFrom or :heightFrom is null) " +
        "and (u.appearanceAndCharacter.height < :heightTo or :heightTo is null)" +
        "and (u.appearanceAndCharacter.hairColor in (:hairColor) or coalesce(:hairColor, null) is null)" +
        "and (u.appearanceAndCharacter.smoking in (:smoking) or coalesce(:smoking, null) is null)" +
        "and (u.appearanceAndCharacter.alcohol in (:alcohol) or coalesce(:alcohol, null) is null)" +
        "and (u.appearanceAndCharacter.children in (:children) or coalesce(:children, null) is null)" +
        "and (lf in (:lookingFor) or coalesce(:lookingFor, null) is null or lf is null )")
        //":lookingFor member of u.appearanceAndCharacter.lookingFor" +
        //" or coalesce(:lookingFor, null) is null)")
     public Set<User> getUsers(@Param("sex") String sex, @Param("ageFrom") Date ageFrom, @Param("ageTo") Date ageTo,
                          @Param("maritalStatus") List<MaritalStatus> maritalStatuses, @Param("figure")List<Figure> figures,
                          @Param("heightFrom") Integer heightFrom, @Param("heightTo") Integer heightTo,
                          @Param("hairColor") List<HairColor> hairColors, @Param("smoking")List<Smoking> smokings,
                          @Param("alcohol") List<Alcohol> alcohol, @Param("children") List<Children> children,
                          @Param("lookingFor") List<LookingFor> lookingFor);

     ...
}

我希望能够在所选字段中的每个字段中搜索任何内容,因此可以从lookingFor中匹配任何元素,一个或几个。 我不知道该怎么做。我只是以为我会在调用此方法的服务处添加一个if,如果该值为null,则调用相同的查询,但没有此字段。

0 个答案:

没有答案