Search code examples
javahibernatejpahibernate-criteria

Not able to resolve an embedded entity in Criteria API


I am trying to perform a fetch using Criteria API with restrictions on the variable of an embedded entity. But I am getting the below error,

org.hibernate.QueryException: could not resolve property: cpm of: org.sorabh.SystemEnt

Below is my SystemEnt entity,

@Entity
@Table(name="system")
public class SystemEnt implements Serializable{

    @Id
    @Column(name="pmTpId", nullable = false)
    private int id; 

    @Column(name="pmMeasureId", nullable = false)
    private int pmMeasureId;    

    @OneToOne(fetch=FetchType.EAGER)    
    @JoinColumn(name="pmMeasureId", insertable=false, updatable=false)
    private Cpm cpm; 

    private String mapper;

    public int getId() {
    return id;
    }

    public int getPmMeasureId() {
    return pmMeasureId;
    }

    public Cpm getCpm() {
    return cpm;
    }

    public String getMapper() {
    return mapper;
    }

    public void setId(int id) {
    this.id=id;
    }

    public void setPmMeasureId(int pmMeasureId) {
    this.pmMeasureId=pmMeasureId;
    }

    public void setCpm(Cpm cpm) {
    this.cpm=cpm;
    }

    public void setMapper(int mapper) {
    this.mapper=mapper;
    }

My CpmMeas contains

@Entity
@Table(name="cpm")
public class Cpm implements Serializable{

    @Id
    @Column(name="pmMeasureId", nullable = false)
    private int pmMeasureId; 

    @Column(nullable=false)
    private int pmGranularity
    //getters and setters

    public void setPmMeasureId(int pmMeasureId) {
    this.pmMeasureId=pmMeasureId;
    }

    public int getPmMeasureId() {
    return pmMeasureId;
    }

    public void setPmGranularity(int pmGranularity) {
    this.pmGranularity=pmGranularity;
    }

    public int getPmGranularity() {
    return pmGranularity;
    }

I do the below in my serviceImpl:

Criteria cr = session.createCriteria(SystemEnt.class);
cr.add(Restrictions.like("mapper", "Test", MatchMode.START));
cr.add(Restrictions.eq("cpm.pmGranularity", 1));

I have tried using aliases as suggested in a few other posts on SO, but it doesn't seem to solve the issue. Also, it is not having issues in resolving mapper, i.e only the nested entities and corresponding variables are not getting resolved.


Solution

  • Use alias , as

    Criteria cr = session.createCriteria(SystemEnt.class);
    cr.createAlias("cpm","cpm");
    cr.add(Restrictions.like("mapper", "Test", MatchMode.START));
    cr.add(Restrictions.eq("cpm.pmGranularity", 1));
    

    anyway the field mapper should be a String, in your sample code it is defined as an int. I tested and without a doubt it works fine. enter image description here