【发布时间】:2025-12-07 11:50:02
【问题描述】:
我正在开发一个应用程序,我想从一个表中获取数据,并希望从该数据更新另一个表。我已经在 JSP 中完成了,但现在我刚刚开始使用 hibernate,所以我想在 hibernate 中完成。
我的数据库中有 2 个表 post_table 和 user_table。我正在从 post_table 获取数据并希望从该数据更新 user_table。这是我的 JSP 代码..
String sql = "SELECT uid,SUM(value) AS SumByUID FROM post_table group by uid;"
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
String mySum = rs.getString("SumByUID");
String u_id = rs.getString("uid");
String sql1 = "update user_table set rank='"+mySum+"' where uid='"+u_id+"'";
PreparedStatement pst = con.prepareStatement(sql1);
pst.executeUpdate();
}
我尝试在休眠状态下进行操作,并从 post_table 中获取数据。这是我的实体类 Post.java
@Entity
@Table(name="post_table")
@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).setResultTransformer(Transformers.aliasToBean(Result.class));
ProjectionList projList = Projections.projectionList();
projList.add(Projections.sum("val"), "topValue");
projList.add(Projections.groupProperty("userId"), "uid");
cr.setProjection(projList);
List postList = cr.list();
tx = session.getTransaction();
session.beginTransaction();
tx.commit();
return postList;
}
我从 post_table 获取数据并将结果设置在 Result.java 中。这是我的 Reslut.java
@Entity
@Table(name="user_table")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Result implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="id")
private long id;
@Column(name="rank")
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;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
这是我的控制器
@RequestMapping(value = "/posts", method = RequestMethod.GET)
public @ResponseBody
List<Post> getEmployee() {
List<Post> postList = null;
try {
postList = profileService.getPostList();
} catch (Exception e) {
e.printStackTrace();
}
return postList;
}
请帮助我,因为我无法使用该数据更新 user_table。
【问题讨论】:
-
你有什么错误吗?
-
你在哪里用 hibernate 做更新查询?
-
不,我只完成了一半的工作..我从 post_table 获取数据但想将该数据更新到 user_table
-
我没有写更新查询,因为我不知道怎么写
-
为什么要为此使用休眠?因为你能?还有为什么是 2 个查询,而不仅仅是一个更新查询?
标签: java mysql spring hibernate jsp