【问题标题】:How to get data from database table and update that data into another table in hibernate? I have done it in JSP but i want to do in Hibernate如何从数据库表中获取数据并将该数据更新到休眠中的另一个表中?我已经在 J​​SP 中完成了,但我想在 Hibernate 中完成
【发布时间】:2025-12-07 11:50:02
【问题描述】:

我正在开发一个应用程序,我想从一个表中获取数据,并希望从该数据更新另一个表。我已经在 J​​SP 中完成了,但现在我刚刚开始使用 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


【解决方案1】:

试试下面的代码,希望对你有帮助:)

@SuppressWarnings({ "unchecked", "rawtypes" })
  public List<Result> getPostList() throws Exception {
      session = sessionFactory.openSession();
      tx = session.beginTransaction();

      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.setResultTransformer(Transformers.aliasToBean(Result.class));
      List<Result> postList = cr.list();
      // please make sure that you are using the class field name rather than database field name in below query.
      String updateHql = "update Result set topValue = :topValue where uid = :uid";
      Query query = null;
      for(Result result : postList){
        query=session.createQuery(updateHql);
        query.setLong("topValue", result.getTopValue());
        query.setLong("uid", result.getUid());
        query.executeUpdate();
        session.flush();
      }

      session.flush();
      tx.commit();
      return postList;
  }

【讨论】:

  • 我在方法的返回类型中遇到错误。List 应该是 List 或将 postList 的类型更改为 List
  • 运行项目时出现此错误..... java.lang.ClassCastException: [Ljava.lang.Object;无法在 com.artle.dao.ProfileDataDAOImpl.getPostList(ProfileDataDAOImpl.java:152) 处转换​​为 com.artle.model.Result
  • 和第 152 行。是为(结果结果:postList){
  • 现在有什么错误吗?请查看更新的答案并尝试。
  • 请检查我的 Result.java