【问题标题】:Error in update in jpajpa更新错误
【发布时间】:2016-09-04 03:53:55
【问题描述】:

我在第一次注册时添加 horastotales 时进行更新时遇到问题,代码工作正常,但是当我插入第二个时将我置于 0 并开始添加错误的值字段总和是属性的两倍是执行此操作的代码 这仅在我插入第一个操作时才有效,如果其他值被更改结果

   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(); 
    } }

Show error in this image

【问题讨论】:

  • 如果您说有一些错误,那么为什么不显示在数据存储中执行的 SQL?然后你从那里向后工作。又名“调试”
  • 不在日志中没有显示错误
  • 为什么不使用 find->modigy->merge?对于 id-keyed 实体,这将非常有效且不易出错。并且绝对不需要在三个更新查询中更新一条记录。
  • 更新用于制作其余字段,因为我没有其他办法
  • 谁说在日志中查找错误?我说看看数据存储区中执行的 SQL。调试它!

标签: java jpa


【解决方案1】:

Equipo.idEquipo 的主键?如果是这样,请考虑切换到 JPA 更常见的 find→modify→merge 模式:

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();  
}

我省略了方法的第一部分,因为很难暗示名称的含义,但我希望你已经掌握了这个想法。

【讨论】:

  • sasha 你的代码很好,但是当 horastotales 修改它时,它改变了我所有的记录 horasTrabajadas
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
相关资源
最近更新 更多