Org.hibernate.QueryException: Failed to resolve property, but found another property

I have an 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 object

 @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 select the sleep criteria

 criteria.add(Restrictions.in("crmUser.id", selectedIds)); 

and it works fine. but this criterion is not met.

 criteria.add(Restrictions.in("crmUser.groupId", filterGroupIds)); 

I get an error

 org.hibernate.QueryException: could not resolve property: crmUser.groupId of: crm.entity.CrmLog 
+5
source share
1 answer

This code

 criteria.add(Restrictions.in("crmUser.id", selectedIds)); 

works because of the CrmLog table's CrmUser id as a foreign key column. Therefore, Hibernate does not need to add connections to the SQL query.

To add a restriction to other CrmUser properties, you need to add an alias. This alias tells Hibernate to add a connection to the SQL query.

 criteria.createAlias("crmUser", "user"); criteria.add(Restrictions.in("user.groupId", filterGroupIds)); 

by default, Hibernate adds an internal join. For left connection

 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 (possibly Hibernate 4)

You can assign an alias to the root object. Perhaps such an example is clearer.

 Criteria criteria = session.createCriteria(CrmLog.class, "log"); criteria.createAlias("log.crmUser", "user"); criteria.add(Restrictions.in("user.groupId", filterGroupIds)); 
+4
source

All Articles