springboot~jpa個性化數據操做接口

jap是個全能倉儲

jap把不少數據庫訪問都封裝了,而且提交了默認的一切數據方法簽名的約定,你們按着約定走,能夠不寫SQL語句,而若是比較複雜的狀況,也須要寫SQL,這裏咱們介紹一下查詢和修改的實例方法,有一點要注意,==倉儲的寫操做是沒有返回值==的。java

  • 商品倉儲個性接口
/**
 * 產品個性化接口.
 */
@Repository
public interface ProductDetailRepository extends
    CrudRepository<ProductDetail, Integer>,
    PagingAndSortingRepository<ProductDetail, Integer> {
  @Query("select p from ProductDetail p where UPPER(p.productName) like UPPER(?1)")
  List search(String term);

  @Transactional
  @Modifying
  @Query("UPDATE ProductDetail p SET p.shortDescription = ?2 WHERE p.productId = ?1")
  void updateDescrption(int id, String description);
}
  • controller中能夠直接調用它,當前IOC這塊於spring框架爲咱們實現了,直接使用註解便可
@RestController
@RequestMapping("/products")
public class ProductDetailController {
  private final ProductDetailRepository repository;
  private final ObjectMapper objectMapper;

  @Autowired
  public ProductDetailController(ProductDetailRepository repository, ObjectMapper objectMapper) {
    this.repository = repository;
    this.objectMapper = objectMapper;
  }
 @PutMapping("{id}")
  public HttpEntity search(@PathVariable int id, @RequestParam("q") String des) {
    repository.updateDescrption(id, des);
    return new ResponseEntity<>(HttpStatus.ACCEPTED);

  }
}
  • 對於使用@Query實現寫操做時,須要註釋如下幾點
  1. 方法返回值必須是void
  2. 必須添加 @Transactional和@Modifying註解
  3. SQL代碼裏表名和字段名都是 java裏的實體名,而不是數據庫的
  • 若是不遵循約定,它將出現下面的異常!
    org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations
相關文章
相關標籤/搜索