springboot~jpa个性化数据操作接口

jap是个全能仓储

jap把很多数据库访问都封装了,并且提交了默认的一切数据方法签名的约定,大家按着约定走,可以不写SQL语句,而如果比较复杂的情况,也需要写SQL,这里我们介绍一下查询和修改的实例方法,有一点要注意,仓储的写操作是没有返回值的。

  • 商品仓储个性接口
/**
 * 产品个性化接口.
 */
@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
posted @   张占岭  阅读(933)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2012-08-01 将不确定变为确定~LINQ查询包含对不同数据上下文上所定义项的引用
2011-08-01 XML遍历(LINQ TO XML的魅力)
2011-08-01 cookies可以跨域了~单点登陆(a.com.cn与b.com.cn可以共享cookies)
2011-08-01 EXCEL中如果输入一个数,然后自动让它乘以某个常数(第一列乘6,第二列乘4)
点击右上角即可分享
微信分享提示