spring data jpa的更新是通過save方法來實現的,通常我們會定義一個自增主鍵的ID,默認就是根據該ID作全量更新。
但如果我想在更新時不用ID,而是其他字段,那么只能另選他法了:
在倉庫定義更新方法:
import com.wlf.order.prize.model.OrderItem; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; public interface OrderDao extends JpaRepository<OrderItem, Long> { OrderItem findByOrderId(String orderId); @Modifying @Query("update OrderItem o set o.address = ?1, o.timestamp = ?4 where o.orderId = ?2 and o.timestamp = ?3") void updateAddressByOrderId(String address, String orderId, Long oldTimestamp, Long newTimestamp); }
有幾點需要注意:
1、注解,這里多了@Modifying用來告訴JPA我們是update,但是SQL我們放在@Query里;
2、SQL,這里不是你數據庫中的表,而是你定義的表實體類,字段也是表實體類對應的屬性;
3、參數,通過?數字的形式來告訴JPA,我們的SQL對應方法的哪個參數;
4、最后我們需要給更新加上事務,使用spring的@Transactional標注到調用該更新方法上即可:
/** * 修改訂單地址 * * @param orderAddress * @param timestamp */ @Transactional public void modifyOrderAddress(OrderAddress orderAddress, Long timestamp) { if (orderAddress == null || orderAddress.getOrderId() == null || orderAddress.getOrderId().trim().equals("") || orderAddress.getAddress() == null || orderAddress.getAddress().trim().equals("")) { log.error("orderAddress is null. orderAddress : {}", orderAddress); throw new OrderException(1004, "更新訂單地址時訂單數據錯誤."); } // 先查詢,已存在數據則更新 OrderItem tmp = orderDao.findByOrderId(orderAddress.getOrderId()); Long tmpTime = null; if (tmp == null) { log.error("orderAddress has not insert."); throw new OrderException(1005, "更新地址時訂單尚未存在."); } // 更新數據 tmpTime = tmp.getTimestamp(); try { orderDao.updateAddressByOrderId(orderAddress.getAddress(), orderAddress.getOrderId(), tmpTime, timestamp); } catch (Exception e) { log.error("db error : {}", e.getMessage()); throw new OrderException(1020, "數據庫操作失敗."); } }