最近开发遇到的一些查询用例,简单记录下
一、定义Repository
@Repository
public interface TransTaskManager extends JpaRepository
二、Repository查询语句
1,对象作为参数传输
@Modifying
@Transactional
@Query("update TransTask t set t.flowStatus =:#{#transTask.flowStatus} where t.flowStatus =:#{#oldStatus}")
int updateFlowStatus(@Param("transTask") TransTask transTask, @Param("oldStatus") int oldStatus);
2,字符串作为参数:
@Modifying
@Transactional
@Query("update TransTask t set t.transId =:transId where t.taskId =:taskId")
int updateTransId(@Param("transId") String transId, @Param("taskId") String taskId);
3,参数定位
@Query(" from TransTask t where t.taskId = ?1 and t.taskName like ?2 and t.flowStatus=100 and t.isDelete=2 ")
Page
4,原生sql
@Query(value = "select t.playUrl from ty_trans_task t where t.taskId =:taskId", nativeQuery = true)
String getPlayUrls(@Param("taskId") String taskId);
5,Example_实例查询
Person person = new Person();
person.setFirstname("Dave"); //Firstname = 'Dave'
ExampleMatcher matcher = ExampleMatcher.matching() .withMatcher("name", GenericPropertyMatchers.startsWith()) //姓名采用“开始匹配”的方式查询
.withIgnorePaths("int"); //忽略属性:是否关注。因为是基本类型,需要忽略掉
Example
6,specification查询
@Transactional(readOnly = true)
public Page query(TransTaskReq req) {
PageRequest pageRequest = new PageRequest(req.getPageNum(), req.getPageSize(), Sort.Direction.valueOf(req.getOrder()), req.getSort());
Specification specification = new Specification() {
@Override
public Predicate toPredicate(Root root, CriteriaQuery> query, CriteriaBuilder cb) {
List predicates = new ArrayList<>();
//任务编号
if (StringUtils.isNotBlank(req.getTaskId())) {
predicates.add(cb.equal(root.get("taskId").as(String.class), req.getTaskId()));
}
//任务名称
if (StringUtils.isNotBlank(req.getTaskName())) {
predicates.add(cb.like(root.get("taskName").as(String.class), "%" + req.getTaskName() + "%"));
}
// in 第一种写法
Expression exp = root.get("id");//root.get("id").as(String.class)
predicates.add(exp.in(noticeIds));
// in 第二种写法
CriteriaBuilder.In