[FIXED] Wie erstellt man eine CriteriaQuery-Prädikat-IN-Klausel mit mehreren Spalten?

Ausgabe

Gegeben ein Predicateused in a CriteriaQuery, zB das:

Predicate predicate = root.get(MyTable.col1).in("col1Val1", "col1Val2");

Kann dies erweitert werden, um mehrere UND-verknüpfte Felder zu verwenden, z. B. die gleichen wie in der folgenden SQL?

SELECT *
FROM MyTable
WHERE (col1, col2, col3) IN (
    ("col1Val1", "col2Val1", "col3Val1"),
    ("col1Val2", "col2Val2", "col3Val2")
);

Lösung

Nicht so elegante Methode mit dem JPA-Kriterien-Builder

    Path<String> col1Path=root.get("col1");
    Path<String> col2Path=root.get("col2");
    Path<String> col3Path=root.get("col3");

    Predicate p0=criteriaBuilder.concat(col1Path,col2Path,col3Path)
         .in("col1Val1"||"col2Val1"||"col3Val1",
              "col1Val2"|| "col2Val2"|| "col3Val2");

Zweite Methode

    Path<String> col1Path=root.get("col1");
    Path<String> col2Path=root.get("col2");
    Path<String> col3Path=root.get("col3");

    Predicate p1=criteriaBuilder.or(
          criteriaBuilder.and(criteriaBuilder.equal(col1Path,"col1Val1"),
                              criteriaBuilder.equal(col2Path,"col2Val1"),
                              criteriaBuilder.equal(col3Path,"col3Val1") 
                              ), 
          criteriaBuilder.and(criteriaBuilder.equal(col1Path,"col1Val2"),
                   criteriaBuilder.equal(col2Path,"col2Val2"),
                   criteriaBuilder.equal(col3Path,"col3Val2") 
                   )
           );


Beantwortet von –
Massimo Petrus


Antwort geprüft von –
Willingham (FixError Volunteer)

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like