SpringBoot JPA中使用中如何写原生SQL

@Query(nativeQuery=true,value = "") value里写正常sql语句
如果返回的是数据库对应的实体对象,那么sql的返回结果集字段别名中应该与该实体类中对应的数据库字段名一致,可以有多余字段,但不能少字段,nativeQuery代表本地数据库的sql语句

上一个稍微复杂的sql, 占位符用" : ",

public interface TXhCodeRepository extends JpaRepository<TXhCodeEntity, Integer> { 
 
 // 查询区电话号码中的最大值
    @Query(nativeQuery = true, value =
            "select * from t_xh_code WHERE tel_code = :cityCode AND count = " +
            "(select MAX(count) from t_xh_code WHERE tel_code = :cityCode)")
    TXhCodeEntity findMaxXhCode(@Param("cityCode") String cityCode);

}

如果你想用分页, 则使用Pageable 入参例如:

@Query("SELECT m FROM Misaka m WHERE m.id>4")
    Page<Misaka> search(Pageable pageable);

猜你喜欢

转载自blog.csdn.net/weixin_38399962/article/details/82756223