我试图使用以下Hibernate查询语言更新数据库表
@RequestMapping(value = "/update",method = RequestMethod.POST)
public @ResponseBody String update(@RequestParam(value = "score1",required = true) String score1,
@RequestParam(value = "score2",required = true) String score2,
@RequestParam(value = "score3",required = true) String score3,
@RequestParam(value = "score4",required = true) String score4,
@RequestParam(value = "id",required = true)String id,
Model model)
{
SessionFactory sessionFactory=new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(User.class)
.addAnnotatedClass(UserDetail.class)
.addAnnotatedClass(UserScores.class).buildSessionFactory();
Session session=sessionFactory.getCurrentSession();
try
{
System.out.println("ID is"+id);
session.beginTransaction();
session.createQuery("update UserScores u set " +
"u.score1=:score1," +
"u.score2=:score2," +
"u.score3=:score3," +
"u.score4=:score4 where u.ID=:id")
.setParameter("score1",score1)
.setParameter("score2",score2)
.setParameter("score3",score3)
.setParameter("score4",score4)
.setParameter("id",id);
session.getTransaction().commit();
session.close();
}
catch (Exception e)
{
System.out.println(e);
}
return score1+score2+score3+score4;
}
执行此代码后,它没有给出任何错误,但数据库中的数据未更新
执行此代码有什么问题
答案 0 :(得分:0)
它起作用了,我尝试了另一种方式
@RequestMapping(value = "/update",method = RequestMethod.POST)
public @ResponseBody String update(@RequestParam(value = "score1",required = true) String score1,
@RequestParam(value = "score2",required = true) String score2,
@RequestParam(value = "score3",required = true) String score3,
@RequestParam(value = "score4",required = true) String score4,
@RequestParam(value = "id",required = true)String id,
Model model)
{
SessionFactory sessionFactory=new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(User.class)
.addAnnotatedClass(UserDetail.class)
.addAnnotatedClass(UserScores.class).buildSessionFactory();
Session session=sessionFactory.getCurrentSession();
try
{
session.beginTransaction();
System.out.println("ID is"+id);
UserScores userScores=session.get(UserScores.class,Integer.parseInt(id));
userScores.setScore1((Double.parseDouble(score1)));
userScores.setScore2((Double.parseDouble(score2)));
userScores.setScore3((Double.parseDouble(score3)));
userScores.setScore4((Double.parseDouble(score4)));
session.update(userScores);
session.getTransaction().commit();
session.close();
}
catch (Exception e)
{
System.out.println(e);
}
答案 1 :(得分:0)
您正在创建的查询需要使用 query.executeUpdate()
执行session.beginTransaction();
Query query = session.createQuery("update UserScores u set " +
"u.score1=:score1," +
"u.score2=:score2," +
"u.score3=:score3," +
"u.score4=:score4 where u.ID=:id");
query.setParameter("score1",score1)
query.setParameter("score2",score2)
query.setParameter("score3",score3)
query.setParameter("score4",score4)
query.setParameter("id",id);
query.executeUpdate();
session.getTransaction().commit();
session.close();
另一种方法是对持久性实体进行更改。在这种情况下,更新将自动传播。