我需要为某个学生存储实验室点,第一个Select可以正常工作,但是当我尝试使用WHERE子句为lab_points更新新值时,程序崩溃。当我跳过WHERE时,程序运行正常,但所有值均已更改。
UPDATE会出现什么问题?
EntityManagerFactory emf = (EntityManagerFactory)getServletContext().getAttribute("emf");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
EntityManager updateEm = emf.createEntityManager();
String nume, prenume;
int lab_points;
for(List<String> linie: linesAsList)
if(linie.get(1).matches("[a-zA-Z- ]+") && linie.get(2).length()>=2) {
nume = linie.get(1).split(" ")[0];
prenume = linie.get(1).split(" ")[1];
lab_points = (Integer) em.createQuery("select n.lab_points from Record as n where n.student.nume=:nume and n.student.prenume=:prenume and n.student.grupa=:grupa and n.cours.numeCurs=:curs")
.setParameter("nume", nume).setParameter("prenume", prenume)
.setParameter("grupa",linie.get(2)).setParameter("curs","Programare avansata").getSingleResult();
lab_points = lab_points + Integer.parseInt(linie.get(3).trim());
System.out.println(lab_points);
updateEm.getTransaction().begin();
updateEm.createQuery("update Record as n set n.lab_points=:points where n.student.nume=:nume").setParameter("nume",nume)
.setParameter("points",lab_points)
.executeUpdate();
updateEm.getTransaction().commit();
System.out.println(em.createQuery("select n.lab_points from Record as n where n.student.nume=:nume and n.student.prenume=:prenume and n.student.grupa=:grupa and n.cours.numeCurs=:curs")
.setParameter("nume", nume).setParameter("prenume", prenume)
.setParameter("grupa", linie.get(2)).setParameter("curs", "Programare avansata").getSingleResult());
}
if (updateEm.getTransaction().isActive())
updateEm.getTransaction().rollback();
updateEm.close();
if (em.getTransaction().isActive())
em.getTransaction().rollback();
em.close();
这是我的数据库错误消息:error
答案 0 :(得分:1)
JPQL不允许
这样的语句n.student.nume
在UPDATE语句中,因为它将尝试转换为UPDATE语句中不允许的SQL JOIN。不幸的是,JPQL不支持UPDATE语句中的子查询。
因此,唯一的解决方案是将student_id映射到Record实体中的属性
@Column(name = "student_id", insertable=false, updatable=false)
private Long authorId;
然后将任务分成两个这样的查询:
List<Long> ids = em.createQuery("SELECT s.id FROM Student s WHERE s.nume = :nume", Long.class)
.setParameter("nume", nume)
.getResultList();
em.createQuery("UPDATE Record r SET r.lab_points = :points WHERE b.student_id IN :ids")
.setParameter("ids", ids)
.setParameter("points",lab_points)
.executeUpdate();