简体   繁体   中英

JPA can not update entity

My problem is when I create a debit I can see it created on Database, bu the "amount" I changed later in the method is never reflected to DB, what am I missing here?

void createDebit(){

  Debit debit=new Debit();
  entityManager.persist(debit);
  entityManager.merge(debit);       
  entityManager.flush();

 //calculate some stuff, do other things

  debit.changeAmount(100);
  entityManager.merge(debit);   
  entityManager.flush(); 
}

you need to persist the data after setting your bean with required data. It seems that you are not setting anything when you persist for first time so if you have some auto-generated key there then it is visible in table and rest of the column seems nullable. In the second block when you are trying to merge you should first get the data stored in DB and then set amount on it. This should work.

Although I cannot understand why you are persisting data like this in two stages.

void createDebit(){

  Debit debit=new Debit();
  entityManager.persist(debit);
  entityManager.merge(debit);       
  entityManager.flush();

 //calculate some stuff, do other things
***//Get Above Debit data from DB and then set amount.***

  debit.changeAmount(100);
  entityManager.merge(debit);   
  entityManager.flush(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM