Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 976
user5620472 Avatar asked May 06 '16 04:05

user5620472


1 Answers

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));
like image 116
v.ladynev Avatar answered Oct 12 '22 22:10

v.ladynev