Java 如何更新hiberbate中的值数组
我正在尝试使用Hibernate更新值数组。当我这样做时,行会被更新,但每次我将受行影响的值设置为1时。为什么?Java 如何更新hiberbate中的值数组,java,hibernate,orm,Java,Hibernate,Orm,我正在尝试使用Hibernate更新值数组。当我这样做时,行会被更新,但每次我将受行影响的值设置为1时。为什么? public int promoteStudentsToNextClass(String[] studentsRefrenceIDS,String promotedClassValue) { int r = 0; Session session = null; Transaction tx = null; try {
public int promoteStudentsToNextClass(String[] studentsRefrenceIDS,String promotedClassValue) {
int r = 0;
Session session = null;
Transaction tx = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();
String hql = "update StudentDTO set studentClassName=? where studentReferenceID=?";
Query query = session.createQuery(hql);
for (int i = 0; i < studentsRefrenceIDS.length; i++) {
query.setParameter(0, promotedClassValue);
query.setParameter(1, studentsRefrenceIDS[i]);
r=query.executeUpdate();
System.out.println("row updated "+r);
}
tx.commit();
return r;
} catch (HibernateException he) {
he.printStackTrace();
tx.rollback();
}
return r;
}
每次使用executeUpdate()方法执行大容量更新时,都会绕过内存中的PersistenceContext(jpa术语),直接进入数据库并执行任何查询 对于像save()、saveOrUpdate()或简单地使用find()获取实体并对其进行修改这样的操作,情况并非如此。它们操作PersistenceContext而不直接访问数据库。当事务方法处理完成,并且无论做了什么更改,都会立即刷新,这是自动完成的 如果希望在给定事务中只更新一次数据库,请尝试执行以下操作:
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();
for (int i = 0; i < studentsRefrenceIDS.length; i++) {
StudentDTO student = session.find(StudentDTO.class, studentsRefrenceIDS[i]);
student.setStudentClassName(promotedClassValue);
}
tx.commit();
SessionFactory SessionFactory=HibernateUtil.getSessionFactory();
session=sessionFactory.openSession();
tx=session.beginTransaction();
对于(int i=0;i
查看这不是批量更新,即使没有正确给出受行影响的值。请在使用executeUpdate()时再次查看问题。。它被称为“批处理/批量更新”,无论您试图影响查询中的一行还是多行,这都无关紧要。
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();
for (int i = 0; i < studentsRefrenceIDS.length; i++) {
StudentDTO student = session.find(StudentDTO.class, studentsRefrenceIDS[i]);
student.setStudentClassName(promotedClassValue);
}
tx.commit();