Hibernate IN Clause with multiple columns

后端 未结 3 788
臣服心动
臣服心动 2020-12-01 21:59

Need to know how to construct a Hibernate Query which fetches results matching an IN clause containing multiple column values.

e.g.,

Que         


        
3条回答
  •  悲哀的现实
    2020-12-01 22:29

    Putting down here how I implemented this. Basically we need to make a Hibernate Component (read @Embeddable object) out of the set of columns we need to query on and embed it in the main Entity.

    The group of columns can be combined as below:

    @Embeddable
    public class CompositeColumns{
      private String col1;
      private String col2;
    
      //Empty constructor is required by Hibernate for instantiation
      public CompositeColumns(){
      }
    
      public CompositeColumns(String col1, String col2){
                this.col1 = col1;
                this.col2 = col2;
          }
    
      @Column(name="COL1")
      public String getCol1(){
      }
      ...
      ... 
      //Rest of getters and setters
    }
    



    Embed the above in your main entity class as below:

    @Entity
    public class MyEntity{
     @Id
     private Integer id;
     private String col3;
     private String col4
     @Embedded
     private CompositeColumns pairedCol1Col2;
     ...
     ...
     //Getters Setters
    
    }
    



    The query would then look as below:

    List cols = //get a list of CompositeColumns type
    
    Query query=session.createQuery( "from MyEntity where pairedCol1Col2 in (:list)" );
    query.setParameterList( "list", list );
    


    This does the job.

    Note: I ran this on an Oracle database

提交回复
热议问题