jpa,querydsl
[TOC]
# jpa## 生成通用模板
实现自定义方法有两种方法:
1. 根据衍生规则进行实现,此种情况简单;查询方法衍生规则 http://docs.spring.io/spring-data/jpa/docs/1.10.1.RELEASE/reference/html/#repositories.query-methods.query-creation
2. 自己编写接口 OrderRepositoryExt
- 在接口中添加自定义方法
- OrderRepository继承此接口
- OrderRepositoryImpl 实现此接口,这个实现类命名规则是一定的,在OrderRepository的基础上加Impl;spring基础会探测到此种情况,注入OrderRepository就可以了
### OrderRepository
```
public interface OrderRepository extends PagingAndSortingRepository<OrderEntity, String>, QueryDslPredicateExecutor<OrderEntity>, OrderRepositoryExt {
/**
* 根据渠道号和订单编号查询订单
*
* @param orderNo
* @param chanNo
* @return
*/
public OrderEntity findFirstByOrderNoAndChanNo(String orderNo, String chanNo);
}
```
### OrderRepositoryExt
```
public interface OrderRepositoryExt {
public OrderEntity findByOrderNo(String orderNo);
}
```
### OrderRepositoryImpl
```
public class OrderRepositoryImpl implements OrderRepositoryExt {
@Autowired
private OrderRepository orderRepository;
@Override
public OrderEntity findByOrderNo(String orderNo) {
QOrderEntity qOrderEntity = QOrderEntity.orderEntity;
Predicate predicate = qOrderEntity.orderNo.eq(orderNo);
return orderRepository.findOne(predicate);
}
}
```
### 使用方法
```
@RestController
@RequestMapping("/test")
public class OrderController {
private static Logger log = LoggerFactory.getLogger(OrderController.class);
@Autowired
private OrderRepository repository;
@RequestMapping("/orders")
public Object order() {
OrderEntity orderEntity = new OrderEntity();
orderEntity.setId(UUID.randomUUID().toString());
orderEntity.setAccountId("111");
orderEntity.setAmount(new BigDecimal(10));
orderEntity.setChanNo("1111");
orderEntity.setCreateAt(new Date());
orderEntity.setOrderNo(UUID.randomUUID().toString());
orderEntity.setOrderStatus("execed_success");
orderEntity.setOrderType("INVEST");
orderEntity.setProductId("2222");
orderEntity.setTransactTime(new Date());
orderEntity.setProductName("12312");
orderEntity.setUpdateAt(new Date());
repository.save(orderEntity);
log.info("save-{}", JSONUtil.toJson(repository.findFirstByOrderNoAndChanNo(orderEntity.getOrderNo(), orderEntity.getChanNo())));
orderEntity.setProductName("update");
repository.save(orderEntity);
log.info("update-{}", JSONUtil.toJson(repository.findByOrderNo(orderEntity.getOrderNo())));
log.info("all ={}", JSONUtil.toJson(repository.findAll()));
List<String> ids = new ArrayList<>();
ids.add("11111");
return null;
}
```