Article Directory
JPA condition query and pagination: JPA condition query + pagination
1. Preparation
pom dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
yml configuration file
server:
port: 9001
spring:
application:
name: tensquare-base # 服务名字,用于服务调用.不能写_ springcloud不识别
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.87.128:3306/tensquare_base?characterEncoding=utf-8
username: root
password: 123456
jpa: # SpringDataJPA的 配置
database: mysql
show-sql: true
Entity class
@Entity // 声明这是一个JPA的实体类 与 数据表对应
@Table(name="tb_label") // 与数据表名对应
public class Label {
@Id
private String id;//
// 因为字段与数据库一致 所以没有加注解
// 如果属性与字段不一致 需要使用@Column
private String labelname;//标签名称
private String state;//状态
private Long count;//使用数量
private Long fans;//关注数
private String recommend;//是否推荐
// get set 方法
// 构造方法
}
Second, add, delete, modify and check
Controller
package com.lsh.controller;
import com.lsh.model.Label;
import com.lsh.service.LabelService;
import com.lsh.util.ResultObject;
import com.lsh.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author :LiuShihao
* @date :Created in 2020/10/28 8:59 下午
* @desc :
*/
@RestController
@RequestMapping("/base")
public class BaseController {
@Autowired
LabelService labelService;
@GetMapping
public ResultObject findAll(){
List<Label> list = labelService.findAll();
return new ResultObject(true, StatusCode.OK,"查询成功",list);
}
/**
* 根据Id查标签
*/
@GetMapping("/{labelId}")
public ResultObject findById(@PathVariable String labelId) {
Label label = labelService.findById(labelId);
return new ResultObject(true, StatusCode.OK,"查询成功",label);
}
/**
* 增加标签
*/
@PostMapping
public ResultObject add(@RequestBody Label label) {
labelService.add(label);
return new ResultObject(true, StatusCode.OK,"增加成功");
}
/**
* 修改标签
*/
@PutMapping("/{labelId}")
public ResultObject update(@PathVariable String labelId,@RequestBody Label label) {
label.setId(labelId);
labelService.update(label);
return new ResultObject(true, StatusCode.OK,"修改成功");
}
/**
* 修改标签
*/
@DeleteMapping("/{labelId}")
public ResultObject deleteById(@PathVariable String labelId) {
labelService.deleteById(labelId);
return new ResultObject(true, StatusCode.OK,"删除成功");
}
}
service
package com.lsh.service;
import com.lsh.model.Label;
import java.util.List;
/**
* @author :LiuShihao
* @date :Created in 2020/10/28 9:01 下午
* @desc :
*/
public interface LabelService {
List<Label> findAll();
Label findById(String labelId);
void add(Label label);
void update(Label label);
void deleteById(String labelId);
}
serviceImpl
package com.lsh.service.Impl;
import com.lsh.model.Label;
import com.lsh.repository.LabelRepository;
import com.lsh.service.LabelService;
import com.lsh.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author :LiuShihao
* @date :Created in 2020/10/28 9:02 下午
* @desc :
*/
@Service
public class LabelServiceImpl implements LabelService {
@Autowired
LabelRepository repository;
@Autowired
IdWorker idWorker;
@Override
public List<Label> findAll() {
return repository.findAll();
}
@Override
public Label findById(String labelId) {
return repository.findById(labelId).get();
}
@Override
public void add(Label label) {
// 使用雪花算法获得id
label.setId(idWorker.nextId()+"");
// 添加用save
repository.save(label);
}
@Override
public void update(Label label) {
// 更新用save
repository.save(label);
}
@Override
public void deleteById(String labelId) {
repository.deleteById(labelId);
}
}
Repository
package com.lsh.repository;
import com.lsh.model.Label;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author :LiuShihao
* @date :Created in 2020/10/28 9:03 下午
* @desc :
*/
public interface LabelRepository extends JpaRepository<Label,String>, JpaSpecificationExecutor<Label> {
}
Three, the use of custom query methods
There is a query generator mechanism based on method names in the internal infrastructure, which is useful for constructing constraint queries on entities in the repository. The mechanism methods are prefixed with
find...By, read...By, query...By, count...By, and get...By. From these methods, the rest of it (fields in the entity) can be analyzed.
For example, the entity class:
@Entity
@Table(name = "tb_enterprise")
public class Enterprise {
@Id
private String id; // id
private String name; // 公司名
private String summary; // 公司简介
private String address; // 公司地址
private String labels; // 公司所有标签
private String coordinate; // 坐标
private String ishot; // 是否热门
private String logo; // logo
private String jobcount; // 职位数
private String url;
Repository:
public interface EnterpriseRepository extends
JpaRepository<Enterprise,String>,JpaSpecificationExecutor<Enterprise> {
// 是否热门
List<Enterprise> findByIshot(String isHot);
}
Entity class:
@Entity
@Table(name = "tb_recruit")
public class Recruit {
@Id
private String id; //
private String jobname; // 职位名称
private String salary; // 薪资范围
private String condition; //经验要求
private String education; //学历要求
private String type; //任职方式
private String address; //办公地址
private String eid; //企业ID
private String createtime; //创建日期
private String state; //状态
private String url; //网址
private String label; //标签
private String content1; //职位描述
private String content2; //职位要求
Repository
public interface RecruitRepository extends
JpaRepository<Recruit,String>,
JpaSpecificationExecutor<Recruit>{
// 推荐职位 为2,根据Createtime倒序,取前2条数据
List<Recruit> findTop2ByStateOrderByCreatetimeDesc(String state);
// 最新职位 : state不为0, 根据Createtime倒序,取前2数据
List<Recruit> findTop2ByStateNotOrderByCreatetimeDesc(String state);
}
Four, custom SQL statements to achieve complex SQL queries
SpringDataJpa's @Query annotation uses custom written sql statements to implement complex sql queries
public interface ProblemDao extends JpaRepository<Problem,String>,JpaSpecificationExecutor<Problem>{
// 最新回答列表 :
// Pageable pageable 用于分页
// 有nativeQuery = true时,是可以执行原生sql语句
// 没有nativeQuery = true 是以jpql 的形式执行,表名是类名,字段是属性
// 返回的Page是SpringData提供的
@Query(value = "SELECT * FROM tb_problem, tb_pl WHERE id = problemid AND labelid=? ORDER BY replytime DESC", nativeQuery = true)
public Page<Problem> newlist(String labelid, Pageable pageable);
// 热门回答列表
@Query(value = "SELECT * FROM tb_problem, tb_pl WHERE id = problemid AND labelid=? ORDER BY reply DESC", nativeQuery = true)
public Page<Problem> hotlist(String labelid, Pageable pageable);
// 等待回答列表
@Query(value = "SELECT * FROM tb_problem, tb_pl WHERE id = problemid AND labelid=? AND reply=0 ORDER BY createtime DESC", nativeQuery = true)
public Page<Problem> waitlist(String labelid, Pageable pageable);
}
Five, custom SQL statements to achieve complex SQL additions, deletions and changes
The @Query annotation of SpringDataJpa uses @Modifying to customize the writing of sql statements to realize the addition, deletion and modification of sql.
@Modifying
This annotation is to inform jpa that this is an update or delete operation. During the update or delete operation, this annotation must be added, otherwise an exception will be thrown
. When using @Modifying, a transaction must be added at the calling place, and no transaction cannot be executed normally.
public interface ArticleDao extends JpaRepository<Article,String>,JpaSpecificationExecutor<Article>{
@Modifying // 不加报错,JPA 默认操作,增删改时使用, 在调用的地方必须加事务,没有事务不能正常执行
@Query(value = "UPDATE tb_article SET state=1 WHERE id = ?", nativeQuery = true)
public void updateState(String id);
@Modifying
@Query(value = "UPDATE tb_article SET thumbup=thumbup+1 WHERE id = ?", nativeQuery = true)
public void addThumbup(String id);
}
//参数是一个对象
@Modifying
@Query(value = "UPDATE `user` SET `name` = :#{#user.name}}, `tel` = :#{#user.tel}}, `openID` = :#{#user.openID}}, `message` = :#{#user.message}}, `downdate` = :#{#user.downdate}}, `flag` = :#{#user.flag}}, `latitude` = :#{#user.latitude}}, `longitude` = :#{#user.longitude}} WHERE `id` = :#{#user.id}", nativeQuery = true)
void uploadUserLocaltion(User user);