SpringBoot JPA分页查询指定列并返回指定实体
用习惯Mybatis,没用过jpa 真是各种踩坑了
脑壳疼,一个分页弄老半天,原来就一句话的事情,唉
先来说说正常的JPA如何操作
实体类对应表来创建,举个例子
@Entity
@Table(name = "td_user")
public class TdUser extends BaseModel {
private static final long serialVersionUID = 8659266017517096998L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, name = "id", length = 10)
private Long id;
@Column(nullable = false, name = "partner_id", length = 11)
private Integer partnerId;
@Column(nullable = false, name = "username", length = 32, unique = true)
private String username;
@Column(name = "nickname", length = 64)
private String nickname;
@JsonIgnore
@Column(nullable = false, name = "password", length = 16)
private String password;
相对应的建立操作接口
@Repository
public interface TdUserRepository extends JpaRepository<TdUser, Long>, JpaSpecificationExecutor<TdUser> {
}
分页查询的时候只要一句话
// Partner partner 外部传入的分页信息
Page<TdUser> allPage = TdUserRepository.findAll(pageable);
但是有时候可能不需要返回所有字段,只要返回一部分而已,经过各种尝试,有一种最简单的方法
就是把想要返回的字段再构建成一个实体,实体的属性需要和数据库字段进行映射,然后单独写一个Repository就可以了
比如
@Entity
@Table(name = "td_user")
public class UserVO extends BaseModel {
private static final long serialVersionUID = 8659266017517096998L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, name = "id", length = 10)
private Long id;
@Column(nullable = false, name = "username", length = 32, unique = true)
private String username;
@Repository
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}
调用的时候
// Partner partner 外部传入的分页信息
Page<User> allPage = UserRepository.findAll(pageable);
我一开始也尝试过写sql,但是我发现返回数据会变成Page<Object[]>,经过json数列化以后数据会变成 [ ["1":"string"],...]这种样子而不是key-value的形式
改了n遍后发现这样是最简单的。。。
SpringBoot JPA实现自定义语句分页查询
例:
1.JPA持久层 InvoiceRepository.java
@Repository
public interface InvoiceRepository extends JpaRepository<Invoice, Integer> {
@Query(
value =
"SELECT * from invoice_apply where company_id=?1 and IF (?2 is null ,1=1,status = ?2)",
countQuery =
"select count(*) from invoice_apply where company_id=?1 and IF (?2 is null ,1=1,status = ?2)",
nativeQuery = true)
Page<Map> findInvoice(int companyID, String status, Pageable pageable);
}
2.服务层
@Override
public Map findInvoice(int companyID, String status, Integer page, Integer pageSize) {
Double amount = companyFinanceRepository.findDCompanyFinance(companyID);
//分页查询
Pageable pageable = PageRequest.of(page, pageSize, Sort.Direction.ASC, "id");
Page<Map> invoiceList = invoiceRepository.findInvoice(companyID, status, pageable);
//重组返回结果
Map map = new HashMap();
map.put("invoice_amount", amount);
map.put("list", invoiceList.getContent());//数据列表
map.put("total", invoiceList.getTotalElements());//记录总条数
map.put("current_page", invoiceList.getNumber());//当前页码
return map;
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。