2017-09-06 50 views
0

我對JPA非常陌生 - 我有這種查找方式可以在登錄表上找到用戶..現在,如果我接收到像用戶更改了他們的新信息密碼,我如何更新條目?JPA - Java Spring - 更新條目 - 編輯用戶


所以我找到了用戶 - 讓我們通過他們的電子郵件地址說。

TblLogin acc = tblLoginRepository.findByEmail(email); 

我見過的方法調用 「getTransaction()」

http://www.objectdb.com/java/jpa/persistence/update

所以這樣的事情?

tblLoginRepository.getTransaction().begin(); 
    acc.setPassword("test2"); 
    tblLoginRepository.getTransaction().commit(); 

但是然後我做這樣的事情 - 那就是了嗎?

TblLogin acc = tblLoginRepository.findByEmail(email); 
    acc.setPassword("newpassword"); 

^那就是 - 沒有別的 - 條目被更新?

當用戶註冊時 - 我做了一個saveAndFlush?我不必爲編輯條目做任何事情?

 TblLogin newAcc = tblLoginRepository.saveAndFlush(new TblLogin(
        email, 
        password, 
        pin 
       )); 

回答

0

使用JPA時有大量術語使用。您應該對Entity, EntityManager, Session, Transaction等基本零件有基本的瞭解。getting-started-with-spring-data-jpa會幫助您。例如使用@Transactional可確保使用此批註的裝飾方法在事務中運行。

您還應該檢查出spring-boot-hibernate-session-question。 使用彈簧啓動的倉庫,你可以有這樣的:

TblLogin acc = tblLoginRepository.findByEmail(email); 
acc.setPassword("newpassword"); 
tblLoginRepository.save(acc); 

上述實施提到save()樣子:

public <S extends T> S save(S entity) { 

    if (entityInformation.isNew(entity)) { 
     em.persist(entity); 
     return entity; 
    } else { 
     return em.merge(entity); 
    } 
} 

下一步將學習em.persist()em.flush()之間的區別如記錄here

我希望這個答案能幫助你!