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
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. Commented May 6, 2016 at 6:08

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.