Need to know how to construct a Hibernate Query which fetches results matching an IN
clause containing multiple column values.
e.g.,
Que
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<CompositeColumns> 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
Entity class - create the multiple searchable columns in @Embeddable class as described below.
@Entity
@Table(name="channels_store_images")
@Data
public class ChannelsStoreImages {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private Integer id;
@Embedded
private CompositeColumns compositeColumns;
@Embeddable
@Data
@AllArgsConstructor
public static class CompositeColumns {
@Column(name="partner_id")
private String partnerId;
@Column(name="entity_type")
private String entityType;
public CompositeColumns(){
}
}
}
Then make object of @Embeddable class and and hit the query as described below
public List<ChannelsStoreImages> getChannelsStoreImagesByPartnerIdAndType(List<ChannelsStoreImages.CompositeColumns> shopIdAndType) {
Query dbQuery = masterEntityManager.createQuery("From ChannelsStoreImages
where compositeColumns IN (:query)",ChannelsStoreImages.class);
dbQuery.setParameter("query",shopIdAndType);
List<ChannelsStoreImages> channelsStoreImagesList = dbQuery.getResultList();
return channelsStoreImagesList;
}
What you are asking here is known as the tuple syntax. It is supported by Hibernate but unfortunately many databases do no support it ...
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-tuple