SpringBoot+JPA进行增删改查

4 篇文章 0 订阅
1 篇文章 0 订阅

这篇博客差不多是2018年写的。现在重构一下。

开篇: 项目结构如下。

第一步.POM文件的配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

第二步骤.

application.properties配置



#项目端口配置
server.port=8080
server.address=0.0.0.0
#Mysql数据源配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF8&useSSL=false
spring.datasource.username=root
spring.datasource.password=admin

#JPA相关配置
#项目启动生成数据库
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
#josn数据格式
spring.jackson.serialization.indent-output=true

第三步.

创建实体类。

package com.example.demo.entity;

import javax.persistence.*;

/**
 * @Auther: zyk
 * @Date: 2019-07-16 09:50
 * @Description:
 */
@Table
@Entity
public class Employee {
    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String name;
    @Column
    private String password;
    private String email;
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

第四步。创建Dao层集成JpaRepository

package com.example.demo.dao;
import com.example.demo.entity.Employee;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;


/**
 * @Auther: zyk
 * @Date: 2019-07-16 12:39
 * @Description:
 */
@Repository
public interface EmployeeDao extends JpaRepository<Employee,String> {
    /**
     * jpa的第一种查询方式 根据命名规范来查询
     * @param name 姓名
     * @param password 密码
     * @return 单个员工或者null
     */
    Employee findByNameAndPassword(String name,String password);

    /**
     * HQL 查询,说白了就是根据实体进行查询
     * @param name 姓名
     * @param password 密码
     * @return 单个员工或者null
     */
    @Query(value = "select e from Employee e where name =?1 and password=?2")
    Employee findQueryHql(String name,String password);

    /**
     * 原生sql进行查询
     * @param name 姓名
     * @param email 邮箱
     * @return 单个员工或者null
     */
    @Query(value = "select * from employee  where name =?1 and email=?2",nativeQuery =true)
    Employee findByQuery(String name, String email);

    /**
     * 复杂查询
     * @param spec 拼接的条件语句 如果有很复杂的语句比如 select * from a where a.name ='' ,
     *             a.password ='' or a.name ='' or a.name ='' or a.name in  ('','')
     * @param pageable 分页加排序 Pageable已经将这些事情做好了。
     * @return Page 形式的员工列表
     */
    Page<Employee> findAll(Specification<Employee> spec,Pageable pageable);
}

第五步。创建Service层。

package com.example.demo.service;

import com.example.demo.entity.Employee;
import org.springframework.data.domain.Page;

import java.util.List;

/**
 * @Auther: zyk
 * @Date: 2019-07-16 12:40
 * @Description:
 */
public interface EmployeeService {
    Employee findByNameAndPassword(String name,String password);

    Employee findQueryHql(String name,String password);

    Employee findByQuery(String name, String email);

    Page<Employee> findAll(int page,int size,int id);

    Employee saveEmp(Employee employee);

    Employee updateEmp(Employee employee);
    List<Employee> findAll();

}

 

第六步。创建ServiceImpl层。

 

package com.example.demo.service.impl;

import com.example.demo.dao.EmployeeDao;
import com.example.demo.entity.Employee;
import com.example.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.Predicate;
import java.util.List;


/**
 * @Auther: zyk
 * @Date: 2019-07-16 12:40
 * @Description:
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeDao employeeDao;

    /**
     * jpa的第一种查询方式 根据命名规范来查询
     * @param name 姓名
     * @param password 密码
     * @return 单个员工或者null
     */
    @Override
    public Employee findByNameAndPassword(String name, String password) {
        return employeeDao.findByNameAndPassword(name, password);
    }
    /**
     * HQL 查询,说白了就是根据实体进行查询
     * @param name 姓名
     * @param password 密码
     * @return 单个员工或者null
     */
    @Override
    public Employee findQueryHql(String name, String password) {
        return employeeDao.findQueryHql(name,password);
    }
    /**
     * 原生sql进行查询
     * @param name 姓名
     * @param email 邮箱
     * @return 单个员工或者null
     */
    @Override
    public Employee findByQuery(String name, String email) {
        return employeeDao.findByQuery(name, email);
    }

    /**
     * 复杂查询的实现
     * @param page 页数 从0开始  从0开始 ,从0开始
     * @param size 每页的数据
     * @param id 模糊查询的参数
     * @return
     */
    @Override
    public Page<Employee> findAll(int page,int size,int id) {
        Pageable pageable =new PageRequest(page,size,new Sort(Sort.Direction.DESC,"id"));
        return employeeDao.findAll((Specification<Employee>) (root, query, cb) -> {
            Predicate p1 = cb.like(root.get("id").as(String.class),"%"+id+"%");
            return cb.and(p1);
        },pageable);
    }

    /**
     * 保存员工
     * @param employee 员工实体
     * @return 保存后的员工
     */
    @Override
    public Employee saveEmp(Employee employee) {
        return employeeDao.save(employee);
    }

    /**
     * 修改员工
     * @param employee 员工实体
     * @return 修改后的员工
     */
    @Override
    public Employee updateEmp(Employee employee) {
        return employeeDao.save(employee);
    }

    /**
     * 调用jpa封装好的 查询所有方法
     * @return
     */
    @Override
    public List<Employee> findAll() {
        return employeeDao.findAll();
    }

}

第七步 controller层

package com.example.demo.controller;

import com.example.demo.entity.Employee;
import com.example.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/**
 * @Auther: zyk
 * @Date: 2019-07-16 12:42
 * @Description:
 */
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/emp")
    public Employee save(Employee emp){
        return employeeService.saveEmp(emp);
    }
    @PutMapping("/emp")
    public Employee update(Employee emp){
        return employeeService.updateEmp(emp);
    }

    @GetMapping("/emp/findByNameAndPassword")
    public Employee findByNameAndPassword(String name,String password){
        return employeeService.findByNameAndPassword(name,password);
    }
    @GetMapping("/emp/findQueryHql")
    public Employee findQueryHql(String name,String password){
        return employeeService.findQueryHql(name,password);
    }
    @GetMapping("/emp/findByQuery")
    public Employee findByQuery(String name, String email){
        return employeeService.findByQuery(name,email);
    }

    /**
     *
     * @param page 由于page是从0开始的,但是前端是从1 开始的  所以要减一
     * @param size
     * @param id
     * @return
     */
    @GetMapping("/emp/findAll")
    public Page<Employee> findAll(int page,int size,int id){
        page =page -1;
        return employeeService.findAll(page,size, id);
    }
    /**
     * 调用jpa封装好的 查询所有方法
     * @return
     */
    @GetMapping("/emp/all")
    public List<Employee>  findJpaAll(){
        return employeeService.findAll();
    }
}

至此,整合完毕。
资源在https://download.csdn.net/download/m0_37256801/11438093

如有问题,请联系微信ZouYunke123

 

 

 

 

  • 14
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值