Search code examples
javamysqlhibernatespring-mvccriteria

How to set the criteria result to another pojo class variables in hibernate


I am fetching data from database using criteria and in criteria i am using groupProperty() and sum().

I want to know that i want to update this result into my another table. The way i know is to set the results from here to another pojo class and then update into another table. But i want to know that is there any other way to do this?If there then please suggest me.

Here is my pojo class Post.java

@Entity
@Table(name="post")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="id")
private long id;

@Column(name="uid")
private long userId;

@Column(name="value")
private long val;

public long getId() {
    return id;
}

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

public long getUserId() {
    return userId;
}

public void setUserId(long userId) {
    this.userId = userId;
}

public long getVal() {
    return val;
}

public void setVal(long val) {
    this.val = val;
}
}

Here is my DAO class

@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Post> getPostList() throws Exception {
session = sessionFactory.openSession();
    Criteria cr = session.createCriteria(Post.class);
    ProjectionList projList = Projections.projectionList();
    projList.add(Projections.sum("val"));
    projList.add(Projections.groupProperty("userId"));
    cr.setProjection(projList);
    List postList = cr.list();
    tx = session.getTransaction();
    session.beginTransaction();
    tx.commit();
    return postList;
}
}

And here is my another pojo class Result.java in which i want these two results

public class Result {

private long topValue;
private long uid;
public long getTopValue() {
    return topValue;
}
public void setTopValue(long topValue) {
    this.topValue = topValue;
}
public long getUid() {
    return uid;
}
public void setUid(long uid) {
    this.uid = uid;
}
}

Solution

  • When you use the setResultTransformers method of criteria and add the alias to your add method of ProjectionList, you should get a List of type Result.

    public List<Result> getResultList() throws Exception {
        session = sessionFactory.openSession();
            Criteria cr = session.createCriteria(Post.class);
            ProjectionList projList = Projections.projectionList();
            projList.add(Projections.sum("val"), "topValue");
            projList.add(Projections.groupProperty("userId"), "uid");
            cr.setProjection(projList);
            cr.setResultTransformers(Transformers.aliasToBean(Result.class)
            List postList = cr.list();
            tx = session.getTransaction();
            session.beginTransaction();
            tx.commit();
            return postList;
        }
        }