2016-09-28 86 views
0

目的:通過主鍵的定列表更新同一表中的某些列,並返回有序INT []來指示行更新的成功與否春數據JPA更新多行

查詢(而不是本機):

update MyEntity e set e.col_1 = :v1, e.col_2 = :v2 where e.id in :ids 

彈簧數據JPA方法:

@Modifying(clearAutomatically = true) 
@Transactional 
public int updateCols(@Param("v1") String v1, @Param("v2") String v2, @Param("ids") List<Long> idList); 

彈簧JpaTransactionManager接口用於

問題:1)只有Spring Data JPA,該怎麼做? (由於存在大量代碼,定製存儲庫不是一個選項),我們希望僅通過Spring數據JPA實現等效於JDBC批量更新的效果。

2)彈簧數據JAP是否有可能通過上面的更新方法返回一個小於輸入列表大小的整數?如果發生這種情況,我們如何知道我的輸入列表中的哪一個失敗?以任何順序?

3)注意到上述方法成功完成後,數據庫行根本沒有被更新。我們如何用spring數據jpa強制它與數據庫同步? 4)如果實體更新沒有被Spring數據JPA刷新,那麼即使我們逐一更新而不是批量更新,我們仍然不會看到數據庫更改? 在此先感謝

回答

0

我使用「in」更新多組行。

我使用的查詢更新user_Record設置電子郵件=:UNAME其中id中( 「+ ID +」)用於更新數據表的user_data

CREATE TABLE user_record ( ID VARCHAR(50) NOT NULL COLLATE 'utf16_bin', 電子郵件VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf16_bin', 名稱VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf16_bin', PRIMARY KEY ( ID ) )

@RequestMapping(value = "/updateSums/{id}", method = RequestMethod.GET) 
public String updateFew(@PathVariable String id ,Model model) 
{ 
    EntityManager em = entityManagerFactory.createEntityManager(); 
    id= id.replace(",", "','"); 
    id= "'"+id+"'"; 
    em.getTransaction().begin(); 
    System.out.println(); 
    em.createNativeQuery("update user_Record set email= :uname where id in ("+id+")", UserRecord.class) 
      .setParameter("uname", "[email protected]") 
      .executeUpdate() 
      ; 

    em.getTransaction().commit(); 

    return "user_one"; 
} 

terminal log in this pic

希望它能適合你! !

0

首先,AFAIK Spring Data JPA不能獨立存在,它只是建立在裸露的JPA基礎之上的東西。它需要使用Hibernate或任何其他JPA提供程序。

https://github.com/colonder/Spring-Hibernate-JavaFX-Invoices

看一看我的倉庫。它是Hibernate + Spring Boot + Spring Data JPA + Java FX 8,但我認爲它會對你有所幫助。我的回購遵循MVC模式,並使用Spring事務管理器,就像您的一樣。至於問題3和4 AFAIK Hibernate(因爲這是Spring Data JPA在我的情況下用作提供程序)更新數據庫中的行,而不是在應用程序中。問題應該是數據庫中更新的行在應用程序中不可見,而不是相反。