IN clause with a composite primary key in JPA criteria

前端 未结 3 573
离开以前
离开以前 2021-01-05 09:13

I have a table named group_table in MySQL with only two columns user_group_id and group_id (both of them are of type VARCHAR

3条回答
  •  不知归路
    2021-01-05 09:46

    Try this

            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery cq = cb.createQuery(GroupTable.class);
            Root r = cq.from(GroupTable.class);
            Expression exp = r.get("id"); //EntityPK is your primary composite key class and id is the property name of primary key in GroupTable entity
            Predicate predicate = exp.in(list);
            cq.select(r).where(predicate);
    
            entityManager.createQuery(cq).getResultList();
    

    I have a following table with below structure

    create table EntityA (
            col1 integer not null,
            col2 integer not null,
            description varchar(255),
            primary key (col1, col2)
        )
    

    Following are the entity and composite key classes

    @Entity
    public class EntityA implements Serializable {
    
        @EmbeddedId
        private EntityPK id;
        private String description;
    
    // getters, setteres    
        ...........................
        ............................
    
    
        }
    
    
    @Embeddable
    public class EntityPK implements Serializable {
    
        private int col1;
        private int col2;
    
    // getters, setters, hashcode, equals etc
    

    My test code is

     CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery cq = cb.createQuery(EntityA.class);
            Root r = cq.from(EntityA.class);
            Expression exp = r.get("id");
            Predicate predicate = exp.in(list);
            cq.select(r).where(predicate);
            em.createQuery(cq).getResultList();
    

    The resulting SQL is

    select
            entitya0_.col1 as col1_0_,
            entitya0_.col2 as col2_0_,
            entitya0_.description as descript3_0_ 
        from
            EntityA entitya0_ 
        where
            entitya0_.col1=? 
            and entitya0_.col2=? 
            or entitya0_.col1=? 
            and entitya0_.col2=? 
            or entitya0_.col1=? 
            and entitya0_.col2=?
    

提交回复
热议问题