文章目录
JPA条件查询及分页:JPA条件查询+分页
一、准备
pom依赖
<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配置文件
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 // 声明这是一个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 方法
// 构造方法
}
二、增删改查
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> {
}
三、自定义查询方法的使用
内部基础架构中有个根据方法名的查询生成器机制,对于在存储库的实体上构建约束查询很有用。该机制方法的前缀有
find…By、read…By、query…By、count…By和get…By,从这些方法可以分析它的其余部分(实体里面的字段)。
比如实体类:
@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
@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);
}
四、自定义SQL语句实现实现复杂的sql查询
SpringDataJpa 的@Query注解使用 自定义写sql语句,实现复杂的sql查询
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);
}
五、自定义SQL语句实现实现复杂的sql增删改
SpringDataJpa 的@Query注解使用 @Modifying自定义写sql语句,实现sql 的增删改。
@Modifying
这个注解是通知jpa,这是一个update或者delete操作,在更新或者删除操作时,此注解必须加,否则会抛出异常
使用@Modifying的时候,在调用的地方必须加事务,没有事务不能正常执行
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);