在JPA中更新时出错 [英] Error in update in jpa
问题描述
第一次注册时添加horastotales进行更新时我有一个问题,代码可以正常工作,但是当我插入第二个代码时,将我置于0并开始添加错误的值字段总和是此属性的两倍是执行此操作的代码 仅当其他值被更改的结果时我插入第一个操作时这才有效
I have a problem when making an update when adding the horastotales when registration for the first time the code works fine but when I insert the second placed me at 0 and starts to add up wrong values fields sum are attribute double this is the code with which to do this operation this works only when I insert the first operation if other values are altered results
public void crearHistorial(Equipo equipo) {
historialDao.crearHistorial(equipo, login.getUsuario(), historial.getHorastd(), historial.getUbicacion());
EntityManagerFactory emf = Persistence.createEntityManagerFactory("inventarioPU");
EntityManager em = emf.createEntityManager();
equipo.setNumeroControl(historial.getUbicacion());
equipoDAO.actualizarequipo(equipo, login.getUsuario());
abrirEquipo(equipoID);
Query query = em.createQuery("UPDATE Historial c SET c.horasTrabajadas= c.horastd -" + equipo.getHorastotales() + " WHERE c.equipo.id=" + equipo.getId());
em.getTransaction().begin();
query.executeUpdate();
em.getTransaction().commit();
listahist= bm.buscarHistorial(equipoID);
for (Historial hist : listahist) {
Query query1 = em.createQuery("UPDATE Equipo c SET c.horastotales = c.horastotales +" + hist.getHorasTrabajadas() + " WHERE c.id=" + equipo.getId());
Query query2 = em.createQuery("UPDATE Equipo c SET c.horasmotor= c.horasmotor -" + hist.getHorasTrabajadas() + " WHERE c.id=" + equipo.getId());
Query query3 = em.createQuery("UPDATE Equipo c SET c.horashrida= c.horashrida -" + hist.getHorasTrabajadas() + " WHERE c.id=" + equipo.getId());
em.getTransaction().begin();
query1.executeUpdate();
query2.executeUpdate();
query3.executeUpdate();
em.getTransaction().commit();
} }
推荐答案
Equipo.id
是Equipo
的主键吗?如果是这样,请考虑切换到JPA常见的 find→modify→merge 模式:
Equipo.id
is a primary key for Equipo
? If so, consider switching to a more JPA-common find→modify→merge pattern:
public void crearHistorial(Equipo equipo) {
// ...
// put the Equipo entity in a context
Equipo c = em.find(Equipo.class, equipo.getId());
// modify the entity
for (Historial hist : listahist) {
c.setHorastotales(e.getHorastotales() + hist.getHorasTrabajadas());
c.setHorasmotor(c.getHorasmotor() - hist.getHorasTrabajadas());
c.setHorashrida(c.getHorashrida() - hist.getHorasTrabajadas());
}
// update the entity in a DB
em.getTransaction().begin();
em.merge(c);
em.getTransaction().commit();
}
我省略了方法的第一部分,因为很难建议名称的含义,但我希望您已经明白了.
I omited the first part of a method, because it is hard to suggest meaning of names, but I hope you've caught the idea.
这篇关于在JPA中更新时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!