JPA基本增删改查条件分页及自定义SQL查询

一、准备

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> {
}

三、条件分页查询

 @Override
    public Page<DkhAccount>  searchAccount(DkhAccount account,int pageNumber,int pageSize) {
         pageNumber = pageNumber < 0 ? 1 : pageNumber;
         pageSize = pageSize < 0 ? 10 : pageSize;
        Pageable pageable = PageRequest.of(pageNumber-1,pageSize);
        Specification<DkhAccount> specification = new Specification<DkhAccount>() {
            @Override
            public Predicate toPredicate(Root<DkhAccount> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                
                if (null != account.getAccount() && !"".equals(account.getAccount())){
                    Predicate predicate = criteriaBuilder.like(root.get("account").as(String.class), "%" + account.getAccount() + "%");
                    predicates.add(predicate);
                }
                
                if (null != account.getPhone() && !"".equals(account.getPhone())){
                    Predicate predicate = criteriaBuilder.like(root.get("phone").as(String.class), "%" + account.getPhone() + "%");
                    predicates.add(predicate);
                }
                
                if (null != account.getUseType() && !"".equals(account.getUseType())){
                    Predicate predicate = criteriaBuilder.like(root.get("useType").as(String.class), "%" + account.getUseType() + "%");
                    predicates.add(predicate);
                }
                Predicate[] predicates1 = predicates.toArray(new Predicate[predicates.size()]);
                return criteriaBuilder.and(predicates1);
            }
        };
        Page all = dkhAccountRepository.findAll(specification, pageable);
        return all;
    }

四、带参数查询

一个参数

	
	@Query(value = "select * from user where openID = ?", nativeQuery = true)
    User findByOpenId(String openID);
   

多个参数

 	# 方式一:
@Query ("select u from User u where u.emailAddress = ?1 and name = ?2")
    User findByEmailAndName(String emailAddress, String name);
 	# 方式二:
    @Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
    User findByLastnameOrFirstname(@Param("lastname") String lastname,@Param("firstname") String firstname);

对象

	@Query(value = "UPDATE `dkh_account` SET  `updateTime` = :#{#dkhAccount.updateTime} , `isshare` = :#{#dkhAccount.isshare} ,`useType` = :#{#dkhAccount.useType},`flag` = :#{#dkhAccount.flag} WHERE  `id` = :#{#dkhAccount.id}",nativeQuery = true)
    @Modifying
    void updateAccount(@Param("dkhAccount")DkhAccount dkhAccount);

五、自定义查询方法的使用

内部基础架构中有个根据方法名的查询生成器机制,对于在存储库的实体上构建约束查询很有用。该机制方法的前缀有
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语句

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语句

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);
}
//参数是一个对象
    @Query(value = "UPDATE `dkh_account` SET  `updateTime` = :#{#dkhAccount.updateTime} , `isshare` = :#{#dkhAccount.isshare} ,`useType` = :#{#dkhAccount.useType},`flag` = :#{#dkhAccount.flag} WHERE  `id` = :#{#dkhAccount.id}",nativeQuery = true)
    @Modifying
    void updateAccount(@Param("dkhAccount")DkhAccount dkhAccount);

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Liu_Shihao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值