软件编程
位置:首页>> 软件编程>> java编程>> java jpa如何自定义sql语句

java jpa如何自定义sql语句

作者:java小白-  发布时间:2022-08-04 14:36:52 

标签:java,jpa,自定义,sql

java jpa自定义sql语句

本篇只是为了再次记录自己又学习了jpa的使用,框架原生的通过解析方法名多适用于单表操作,自定义的sql查询则可以解决所有问题,记录些自定义sql语法的记录,以便后续参照。

1.多表关联查询,含条件


@Query(value = "SELECT b FROM QyVideo a JOIN YjQyXx b ON  a.qyId = b.id AND a.cameraId = ?1 ")

2.清空表


@Transactional
@Modifying
@Query(value = "truncate table yj_qy_xx", nativeQuery = true)

注:update、truncate或delete时必须使用@Modifying和@Transactional对方法进行注解,才能使得ORM知道现在要执行的是写操作。

3.模糊查询


@Query("select p from WhpzxryzsXxPo p where p.ryxm like concat('%',?1,'%') and p.cyyxqq >= ?2")

4.查询结果为VO

含两个实体类


@Query(value = "SELECT new com.kun.aqsczt.vo.FxjzfbVo(u, seventinfo) FROM SSmsInfo u left join SEventInfo seventinfo on u.referId = seventinfo.eventId WHERE (:referType IS NULL OR :referType IS '' OR u.referType = :referType) AND (:isSend IS NULL OR :isSend IS '' OR u.isSend = :isSend) ")

5.使用@Param注解注入参数

分页查询


@Query(value = "SELECT a  FROM CEiWorkaccMaybe a " +
           "WHERE (:psnName IS NULL OR :psnName IS '' OR a.psnName LIKE %:psnName%) " +
           "AND (:commName IS NULL OR :commName IS '' OR a.commName LIKE %:commName%) " +
           "AND (:idCard IS NULL OR :idCard IS '' OR a.idCard LIKE %:idCard%) " +
           "AND (:doctorDateStart IS NULL OR :doctorDateStart IS '' OR a.doctorDate >= :doctorDateStart) " +
           "AND (:doctorDateEnd IS NULL OR :doctorDateEnd IS '' OR a.doctorDate <= :doctorDateEnd) "
   )
Page<CEiWorkaccMaybe> getSuspectedWorkAccidentVerification(
           @Param("psnName") String psnName,
           @Param("commName") String commName,
           @Param("idCard") String idCard,
           @Param("doctorDateStart") String doctorDateStart,
           @Param("doctorDateEnd") String doctorDateEnd,
           Pageable pageable
   );

无非是把日常的sql中的表名换成了对应的实体类名,接收参数适用 ?加上第几个参数的几。当然也可使用@Param注解注入参数,就变成了使用 :参数 名称接收。

jpa自定义sql查询结果

很多时候都会遇到自定义sql,自定义返回字段,而不是pojo类。这个情况要通过接口定义返回。

直接上代码


@Query(value = "select m.field AS field,COUNT(m.field) AS size from MigrationObject m where m.xmlName = ?1 and m.groupName = ?2 group by m.field")
   List<WorkCenter> getKey(String xmlName, String groupName);

对于这种情况,只返回了两个字段,就需要定义一个接口来接收(注意AS别名的配置)


public interface WorkCenter {
   String getField();
   String getSize();
}

最后跑一下demo代码


  List<WorkCenter> list = migrationObjectRepository.getKey("EN_Work centerResource.xml","Key");
       for (WorkCenter workCenter:list){
           System.out.println(workCenter.getField());
           System.out.println(workCenter.getSize());
       }

ARBPL
5
SPRAS
2
CANUM
2
ENDDA
1
WERKS
5

来源:https://blog.csdn.net/weixin_42209368/article/details/119649029

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com