I have entity
@Entity
@Table(name = "CRM_LOG")
public class CrmLog implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private @Getter @Setter Long id;
..........
@OneToOne
private @Getter @Setter CrmUser crmUser;
}
and another entity
@Entity
@Table(name = "CRMUSER")
public class CrmUser implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Integer groupId;
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
}
and I make hibernate criteria select
criteria.add(Restrictions.in("crmUser.id", selectedIds));
and it work fine. but this criteria is failed
criteria.add(Restrictions.in("crmUser.groupId", filterGroupIds));
I get an error
org.hibernate.QueryException: could not resolve property: crmUser.groupId of: crm.entity.CrmLog
This code
criteria.add(Restrictions.in("crmUser.id", selectedIds));
works because of CrmLog
table has CrmUser
id
as a foreign key column. So Hibernate doesn't need to add joins in the SQL query.
To add restriction on other CrmUser
properties you need to add an alias. Such alias tells to Hibernate to add join to the SQL request.
criteria.createAlias("crmUser", "user");
criteria.add(Restrictions.in("user.groupId", filterGroupIds));
by default Hibernate adds an inner join. For a left join
criteria.createAlias("crmUser", "user", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.in("user.groupId", filterGroupIds));
JoinType.LEFT_OUTER_JOIN
can be used with Hibernate 5 (maybe Hibernate 4)
You can assign an alias to the root entity. Maybe such example is more clear
Criteria criteria = session.createCriteria(CrmLog.class, "log");
criteria.createAlias("log.crmUser", "user");
criteria.add(Restrictions.in("user.groupId", filterGroupIds));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With