像OneToOne这样的JPA标准加入

时间:2019-06-20 09:38:09

标签: java spring-boot spring-data-jpa criteria

我需要搜索包含字符串参数的数据

我有2个实体:

@Entity
@Table(name = "referentiel_digital")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class ReferentielDigital implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Size(max = 200)
    @Column(name = "libelle_commercial", length = 200, nullable = false)
    private String libelleCommercial;

    @Size(max = 1000)
    @Column(name = "description_courte", length = 1000)
    private String descriptionCourte;

    @Size(max = 1000)
    @Column(name = "description_longue", length = 1000)
    private String descriptionLongue;

    @OneToOne
    @JoinColumn(unique = true)
    private Referentiel reference;

@Entity
@Table(name = "referentiel")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Referentiel implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Column(name = "uuid", nullable = false)
    private UUID uuid;

    ....

    @OneToOne(mappedBy = "reference")
    @JsonIgnoreProperties("referentiels")
    private ReferentielDigital digital;

我开发了使用JPA标准的seach API。它可以在不同的字段上很好地工作,并加入(ManyToOne),但是在这种情况下,我需要找到Referentiel,其中在referentielDigital.descriptionLongue中包含字符串。

我尝试:

        Join<Referentiel, ReferentielDigital> digital = root.join("digital");
        Expression<String> exp1 = digital.get("libelleCommercial");


        Predicate p1 = exp1.in("%" + criteria.getLibelle() + "%");

        Expression<String> exp2 = digital.get("descriptionCourte");
        Predicate p2 = exp1.in("%" + criteria.getLibelle() + "%");

        Expression<String> exp3 = digital.get("descriptionLongue");
        Predicate p3 = exp1.in("%" + criteria.getLibelle() + "%");

        predicates.add(cb.or(p1, p2, p3));

它不起作用,因为请求包含“ in”,并且我希望具有“ like”以获得良好的结果。

对于扩展对象,我没有“喜欢”方法。

请问我该如何要求加入?

1 个答案:

答案 0 :(得分:0)

我通过JB Nizet帮助找到了解决方案:

        Join<Referentiel, ReferentielDigital> digital = root.join("digital");
        Expression<String> exp1 = digital.get("libelleCommercial");

        Predicate p1 = cb.like(exp1, "%" + criteria.getLibelle() + "%");

        Expression<String> exp2 = digital.get("descriptionCourte");
        Predicate p2 = cb.like(exp2, "%" + criteria.getLibelle() + "%");

        Expression<String> exp3 = digital.get("descriptionLongue");
        Predicate p3 = cb.like(exp3, "%" + criteria.getLibelle() + "%");

        predicates.add(cb.or(p1, p2, p3));