二十二、Spring Boot中Spring Data Repository

  JPA对数据的增删改查进行了封装,核心接口就是Repository。下面展示如何使用封装好的API:
(一)新建CustomerRepository

/**
 * 客户仓储
 * @author 咸鱼
 * @date 2018/9/29 22:51
 * SimpleJpaRepository<Customer, Long>:泛型1:持久化的对象类型 泛型2:持久化的对象的主键类型
 */
@Repository
@Transactional(readOnly = false, rollbackFor = RuntimeException.class)
public class CustomerRepository extends SimpleJpaRepository<Customer, Long> {
    /**
     *     这个构造方法是必须是继承SimpleJpaRepository必须要实现的,其中EntityManager参数需要
     * 注入进来,所以这里加了@Autowired注解,自动注入EntityManager对象
     */
    @Autowired
    public CustomerRepository(EntityManager em) {
        super(Customer.class, em);
    }
}

(二)使用CustomerRepository

	private CustomerRepository customerRepository;
    @Autowired
    public CustomerController(CustomerRepository customerRepository){
        this.customerRepository = customerRepository;
    }

    @GetMapping("/{id}")
    public Customer getCustomerById(@PathVariable Long id){
        Optional<Customer> customerOptional = customerRepository.findById(id);
        return customerOptional.orElse(null);
    }

}

(三)异常处理
  问题:若报错:说某个类不能注入,因为其不能实现JDK动态代理
  原因解析:因为只有接口才能实现JDK动态代理,所以如果是类的话,就会报这个错。
  解决办法:改造启动类上的事务管理注解,换成CGLib动态代理@EnableTransactionManagement(proxyTargetClass = true)

猜你喜欢

转载自blog.csdn.net/panchang199266/article/details/82904096