zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Cocos2dx开发(3)——Cocos2dx打包成APK,ANT环境搭建
    Cocos2dx开发(2)——Win8.1下Cocod2dx 3.2环境搭建
    Cocos2dx开发(1)——Win8.1下 NDK r10 环境搭建
    设计模式备忘录(1):适配器模式、依赖注入依赖倒置、空对象模式
    使用latencytop深度了解你的系统的延迟(转)
    操作系统基础
    计算机基础
    说明exit()函数作用的程序
    变量的引用类型和非引用类型的区别
    二进制转16进制JAVA代码
  • 原文地址:https://www.cnblogs.com/lori/p/9402808.html
Copyright © 2011-2022 走看看