org.hibernate.QueryException: could not resolve property but another property is found
Asked Answered
P

1

6

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
Pennant answered 6/5, 2016 at 4:33 Comment(1)
Please post the full hibernate criteria query, it looks to me as if you are using CrmLog as a root and want to restrict the groupId which is CrmUser's property.Putdown
Z
4

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));
Zymogenic answered 6/5, 2016 at 11:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.