我使用条件从数据库中获取数据,并且我正在使用groupProperty()和sum()。
我想知道我想将此结果更新到另一个表中。我知道的方法是将结果从这里设置为另一个pojo类,然后更新到另一个表。但我想知道有没有其他方法可以做到这一点?如果有,那么请建议我。
这是我的pojo类 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;
}
}
这是我的 DAO 类
@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;
}
}
这是我的另一个pojo类 Result.java ,其中我想要这两个结果
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;
}
}
答案 0 :(得分:2)
当您使用条件的setResultTransformers方法并将别名添加到ProjectionList的add方法时,您应该获得Result类型的List。
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;
}
}