2015-07-19 66 views
25

以前曾詢問過此問題,但解決方案未解決問題。我創建一個JUnit測試:不支持使用JPA更新查詢進行DML操作

@Test 
    @Transactional 
    @Modifying 
    public void updateMaterialInventory() throws Exception{ 

     // Initialize the database 
     materialRepository.saveAndFlush(material); 

     long id = material.getId(); 
     materialRepository.updateMaterialInventory(id,UPDATED_INVENTORY_COUNT); 

     assertEquals(material.getInventory_count(), UPDATED_INVENTORY_COUNT, 0); 
    } 

上述試驗正在呼叫的查詢爲:

@Query("UPDATE Material m SET m.inventory_count = ?2 WHERE m.id = ?1") 
    void updateMaterialInventory(Long id,int newInventoryAmount); 

錯誤:

Caused by: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [UPDATE com.htd.domain.Material m SET m.inventory_count = ?2 WHERE m.id = ?1] 
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.errorIfDML(QueryTranslatorImpl.java:318) 
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:369) 
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231) 
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264) 
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103) 
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573) 
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:495) 
    ... 55 more 

回答

61

@Modifying註釋必須放置在updateMaterialInventory方法,沿着@Query註釋,讓Spring數據知道查詢不是用於選擇值的查詢,而是用於更新值。

+2

爲什麼我在更新時出現「執行更新/刪除查詢」異常? – Kenji

+0

@Kenji 加入: @Transactional(propagation = Propagation.REQUIRED,readOnly = false) – user64141

1

據我所知,您不應該在存儲庫類中使用@Transactional註釋。找到下面的答案。

Service Impl class

import org.springframework.transaction.annotation.Transactional; 
... 
@Test 
@Transactional 
public void updateMaterialInventory() throws Exception{ 

    // Initialize the database 
    materialRepository.saveAndFlush(material); 

    long id = material.getId(); 
    materialRepository.updateMaterialInventory(id,UPDATED_INVENTORY_COUNT); 

    assertEquals(material.getInventory_count(), UPDATED_INVENTORY_COUNT, 0); 
} 

Repository class

import org.springframework.data.jpa.repository.Modifying; 
import org.springframework.data.jpa.repository.Query; 
... 

    @Modifying 
    @Query("UPDATE Material m SET m.inventory_count = ?2 WHERE m.id = ?1") 
    void updateMaterialInventory(Long id,int newInventoryAmount); 

確保使用正確的進口。希望這是有幫助的。

相關問題