SpringBoot2.0使用Spring Data-JPA实现增删改查

本文主要讲解使用springboot2.0使用jpa实现增删改查,外加自己拓展方法,spring的jpa是一个非常不错的持久层框架,可以理解为就是对Hibrenate进行了封装,比起Mybatis优点在于不用关注sql语句的编写。我这案例中使用ResultFul风格来编写的。
好了讲了这么多废话直接上代码和步骤吧。使用的是maven管理项目,如果不会maven的同学可以先去学会使用maven吧。

第一步:新建一个springboot项目(pom文件直接拿走吧)



    4.0.0

    com.itpengwei.idea.one
    springboot-jpa
    0.0.1-SNAPSHOT
    jar

    springboot-jpa
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.3.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



第二步:写yml配置文件(我这里写了两个,dev用于开发环境,prod用于生产环境)

SpringBoot2.0使用Spring Data-JPA实现增删改查_第1张图片

application.yml内容如下:

spring:
  profiles:
    active: dev

application-dev.yml如下:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/springboot-test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 19980311
  jpa:
   hibernate:
     ddl-auto: update
   show-sql: true

第三步:创建实体类并且使用注解描述实体和表的关系:

package com.itpengwei.sjpa.pojo;

import javax.persistence.*;

@Entity(name = "tb_student")
public class Student {
    @Id
    @GeneratedValue
    @Column(name = "id", length = 32)
    private Long id;
    @Column(length = 50)
    private String name;
    @Column(length = 3)
    private Integer age;

    public Student() {
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

第四步:写个dao

package com.itpengwei.sjpa.dao;

import com.itpengwei.sjpa.pojo.Student;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
//泛型中第一个参数是实体类,第二个是id类型
public interface StudentDao extends JpaRepository {
    //根据学生姓名查询数据
    public List findByName(String name);
}

是不是发现特别简单这个dao,因为spring为我们封装了大量的方法

第五步:写service


package com.itpengwei.sjpa.service;

import com.itpengwei.sjpa.dao.StudentDao;
import com.itpengwei.sjpa.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class StudentService {
    @Autowired
    private StudentDao studentDao;
    //插入一个学生
    public void addStudent(Student student){
        studentDao.save(student);
    }

    //修改一个学生(jpa是根据id来修改的)
    public void  updateStudent(Student student){
        studentDao.save(student);
    }
    //根据id删除一条数据
    public void deleteStudentById(Long id){
        studentDao.deleteById(id);
    }

    //查询所有
    public List findAll(){
        return studentDao.findAll();
    }
    //根据id查询一条数据(2.0后不能使用findOne了)
    public Student findStudentById(Long id){
        return studentDao.findById(id).get();
    }
    //根据学生姓名查询多条数据
    public List findStudentByName(String name){
        return studentDao.findByName(name);
    }
}

第六步:到controller了:

package com.itpengwei.sjpa.controller;

import com.itpengwei.sjpa.common.CommonResult;
import com.itpengwei.sjpa.pojo.Student;
import com.itpengwei.sjpa.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    //添加一个学生
    @PostMapping(value = "/addStudent")
    public CommonResult addStudent(Student student) {
        CommonResult result = new CommonResult();
        try {
            studentService.addStudent(student);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(500);
            result.setMsg("失败");
            return result;
        }
    }

    //修改一个学生(jpa是根据id来修改的)
    @PutMapping(value = "/updateStudent")
    public CommonResult updateStudentById(Student student) {
        CommonResult result = new CommonResult();
        try {
            studentService.updateStudent(student);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(500);
            result.setMsg("失败");
            return result;
        }
    }

    //根据id删除一条数据
    @DeleteMapping(value = "/deleteStudent/{id}")
    public CommonResult deleteStudentById(@PathVariable(name = "id", required = true) Long id) {
        CommonResult result = new CommonResult();
        try {
            studentService.deleteStudentById(id);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(500);
            result.setMsg("失败");
            return result;
        }
    }

    //查询所有
    @GetMapping(value = "/findAll")
    public CommonResult findAll() {
        CommonResult result = new CommonResult();
        try {
            List list = studentService.findAll();
            //将查询结果封装到CommonResult中
            result.setData(list);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(500);
            result.setMsg("失败");
            return result;
        }
    }

    //根据id查询一条数据(2.0后不能使用findOne了)
    @GetMapping(value = "/findStudentById/{id}")
    public CommonResult findStudentById(@PathVariable(name = "id") Long id) {
        CommonResult result = new CommonResult();
        try {
            Student student = studentService.findStudentById(id);
            //将查询结果封装到CommonResult中
            result.setData(student);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(500);
            result.setMsg("失败");
            return result;
        }
    }

    //根据学生姓名查询多条数据
    @GetMapping(value = "/findStudentByName")
    public CommonResult findStudentByName(String name) {
        CommonResult result = new CommonResult();
        try {
            List studentList = studentService.findStudentByName(name);
            //将查询结果封装到CommonResult中
            result.setData(studentList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(500);
            result.setMsg("失败");
            return result;
        }
    }
}

这里我就讲我这个全局返回类也给贴出来吧

package com.itpengwei.sjpa.common;

import java.util.List;

public class CommonResult {
    private Integer state;
    private String msg;
    private Object data;

    public CommonResult() {
        this.state=200;
        this.msg="成功";
    }

    public CommonResult(Integer state, String msg) {
        this.state = state;
        this.msg = msg;
    }

    public CommonResult(Integer state, String msg, Object data) {
        this.state = state;
        this.msg = msg;
        this.data = data;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

第七步:启动项目开始进行测试:

启动成功,数据库已经创出了表

SpringBoot2.0使用Spring Data-JPA实现增删改查_第2张图片

控制台输出了建表语句

SpringBoot2.0使用Spring Data-JPA实现增删改查_第3张图片

测试添加一个学生:

SpringBoot2.0使用Spring Data-JPA实现增删改查_第4张图片

修改一个学生数据:

SpringBoot2.0使用Spring Data-JPA实现增删改查_第5张图片

根据id删除一条数据:

SpringBoot2.0使用Spring Data-JPA实现增删改查_第6张图片

查询所有数据:

SpringBoot2.0使用Spring Data-JPA实现增删改查_第7张图片

根据id查询一条数据:

SpringBoot2.0使用Spring Data-JPA实现增删改查_第8张图片

根据姓名查询:

SpringBoot2.0使用Spring Data-JPA实现增删改查_第9张图片

你可能感兴趣的:(springboot)