2017-08-27 95 views
1

我使用彈簧數據jpa和postgre的春季開機。我有「item」實體,它具有價格,數量,自動生成的int id和它所屬的順序。 我已經搜索瞭如何編輯只改變其價格和數量的實體,而不創建新的實體,我得到的唯一答案是從數據庫獲取實體並將每個屬性設置爲新的實體,然後保存它。但是,如果我有6個其他屬性,除了價格和數量,這意味着在更新方法中,我將設置一個屬性8次,這在我看來就像太多的春天樣板代碼。我的問題是:是否有更好的/默認的方式來做到這一點?春季開機如何編輯實體

+0

我看沒有完美的解決方案,檢索的入口存儲庫或服務進行更改並調用保存。 –

回答

1

您可以提供copy constructor

public Item(Item item) { 
    this(item.price, item.quantity); 
} 

或使用org.springframework.beans.BeanUtils方法

@RestController 
@RequestMapping("/items") 
public class ItemController { 

    @Autoware 
    private ItemRepo repo; 

    @PutMapping("/{id}") 
    public ResponseEntity<?> update(@PathVariable("id") Item targetItem, @RequestBody Item sourceItem) { 
     BeanUtils.copyProperties(sourceItem, targetItem, "id"); 
     return ResponseEntity.ok(repo.save(targetItem)); 
    } 
} 
+0

這BeanUtills似乎是我正在尋找的東西。非常感謝! –

+0

@TodorAtanasov)),不要忘了給予好評的答案,幫助你... – Cepr0

+0

@ Cerp0我upvoted你,但我沒有足夠的等級,以便它不顯示我的票:),但我選擇了你最好的答案,至少是顯示:) 感謝您的反饋!記錄下名聲低於15的人的投票記錄,但不要更改公開顯示的帖子分數。 –

0

不,你不需要設置任何東西8次。如果您只想更改價格和數量,只需更改這兩項。把它放在一個@Transactional方法:

@Transactional 
public void updateItem(Item item){ 
    // .... 
    // EntityManager em; 
    // .... 

    // Get 'item' into 'managed' state 
    if(!em.contains(item)){ 
     item = em.merge(item); 
    } 

    item.price = newPrice; 
    item.quantity = newQuantity; 
    // You don't even need to call save(), JPA provider/Hibernate will do it automatically. 
} 

這個例子將產生一個SELECTUPDATE查詢。就這樣。

+0

我想我的問題並不清楚。我知道,如果我想只改變價格和數量我會改變(套)價格和​​數量,但如果未來實體我想更新有5個屬性(可以說價格,數量的顏色,材質,投遞員)我將不得不調用 entity.price = newPrice; entitiy.quantity = newQuantity; entity.color = newColor; 等等...... 這正是我想逃避:) –

0

使用@Query註釋和定義update聲明

@Modifying 
@Transactional 
@Query("update Site site set site.name=:name where site.id=:id") 
void updateJustNameById(@Param("id")Long id, @Param("name")String name); 
0

您需要使用自己處理所有的這個春天數據休息嘗試。您只需在指定的URL處調用修補程序請求並提供已更改的實體屬性。如果你有一些關於彈簧數據的知識,可以看看https://github.com/ArslanAnjum/angularSpringApi。在控制器

BeanUtils.copyProperties(sourceItem, targetItem, "id"); 

然後: