原创

SpringBoot 系列教程(十六):SpringBoot集成Spring Data-JPA实现增删改查

版权声明: 本文为博主原创文章,转载请注明原文出处!
本文链接:https://thinkingcao.blog.csdn.net/article/details/85161578

什么是spring data jpa?

spirng data jpa是spring提供的一套简化JPA开发的框架,按照约定好的【方法命名规则】写dao层接口,就可以在不写接口实现的情况下,实现对数据库的访问和操作。同时提供了很多除了CRUD之外的功能,如分页、排序、复杂查询等等。

Spring Data JPA 可以理解为 JPA 规范的再次封装抽象,底层还是使用了 Hibernate 的 JPA 技术实现。

JPA仅仅是一种规范,也就是说JPA仅仅定义了一些接口,而接口是需要实现才能工作的。所以底层需要某种实现,而Hibernate就是实现了JPA接口的ORM框架。

也就是说:

JPA是一套ORM规范,Hibernate实现了JPA规范   ,spring的jpa对Hibrenate进行了封装,比起Mybatis优点在于不用关注sql语句的编写。

 如图:

 

一、新建一个SpringBoot项目,项目名为springboot-data-jap,引入pom依赖

    <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<relativePath />
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>


	<dependencies>
		<!-- springdata jpa依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<!-- mysql驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.36</version>
		</dependency>
		<!-- springboot-web组件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- springboot-test组件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>


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

二:  创建yml配置文件(这里创建两个,dev用于开发环境,prod用于生产环境)

    目录如下:

application.yml内容如下:

spring:
  profiles:
    active: dev   ##指定读取哪个yml环境配置

application-dev.yml如下:

### 开发环境
## 端口配置
server:
  port: 8080
spring:
  datasource: ##数据库配置
    url: jdbc:mysql://localhost:3306/springboot-data-jpa?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
  jpa:  
    database: MYSQL  ##数据库类型
    show-sql: true
    hibernate:
      ddl-auto: update    
    properties:
      hibernate: 
      dialect: org.hibernate.dialect.MySQL5Dialect

application-prod.yml如下:

## 正式环境
server:
  port: 8081
spring:
  datasource: ##数据库配置
    url: jdbc:mysql://localhost:3306/springboot-data-jpa?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
  jpa:  
    database: MYSQL  ##数据库类型
    show-sql: true
    hibernate:
      ddl-auto: update    
    properties:
      hibernate: 
      dialect: org.hibernate.dialect.MySQL5Dialect

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

package com.thingingcao.jpa.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.springframework.format.annotation.DateTimeFormat;

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

	@Column(name = "name", length = 50)
	private String name;

	@Column(name = "age", length = 3)
	private Integer age;

	@Column(name = "createTime")
	@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	private Date createTime;

	@Column(name = "editTime")
	@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	private Date editTime;

	public Student() {

	}

	public Student(Long id, String name, Integer age, Date createTime, Date editTime) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.createTime = createTime;
		this.editTime = editTime;
	}

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

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public Date getEditTime() {
		return editTime;
	}

	public void setEditTime(Date editTime) {
		this.editTime = editTime;
	}

}

四 : 创建StudentDao

package com.thingingcao.jpa.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.thingingcao.jpa.entity.Student;

import java.util.List;

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

  这个dao比较简单,就自定义了一个findByName()方法, 因为继承的JpaRepository里,spring为我们封装了大量的curd方法,直接继承过来用就行了

五 : 创建StudentService

package com.thingingcao.jpa.service;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thingingcao.jpa.dao.StudentDao;
import com.thingingcao.jpa.entity.Student;

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

六 : 创建StudentController

package com.thingingcao.jpa.controller;
 
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import com.thingingcao.jpa.common.ResponseResult;
import com.thingingcao.jpa.entity.Student;
import com.thingingcao.jpa.service.StudentService;
 
@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;
 
    //添加一个学生
    @PostMapping(value = "/addStudent")
    public ResponseResult addStudent(Student student) {
        ResponseResult result = new ResponseResult();
        try {
            studentService.addStudent(student);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(500);
            result.setMsg("失败");
            return result;
        }
    }
 
    //修改一个学生(jpa是根据id来修改的)
    @PutMapping(value = "/updateStudent")
    public ResponseResult updateStudentById(Student student) {
        ResponseResult result = new ResponseResult();
        try {
            studentService.updateStudent(student);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(500);
            result.setMsg("失败");
            return result;
        }
    }
 
    //根据id删除一条数据
    @DeleteMapping(value = "/deleteStudent/{id}")
    public ResponseResult deleteStudentById(@PathVariable(name = "id", required = true) Long id) {
        ResponseResult result = new ResponseResult();
        try {
            studentService.deleteStudentById(id);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(500);
            result.setMsg("失败");
            return result;
        }
    }
 
    //查询所有
    @GetMapping(value = "/findAll")
    public ResponseResult findAll() {
        ResponseResult result = new ResponseResult();
        try {
            List<Student> 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 ResponseResult findStudentById(@PathVariable(name = "id") Long id) {
        ResponseResult result = new ResponseResult();
        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 ResponseResult findStudentByName(String name) {
        ResponseResult result = new ResponseResult();
        try {
            List<Student> studentList = studentService.findStudentByName(name);
            //将查询结果封装到CommonResult中
            result.setData(studentList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(500);
            result.setMsg("失败");
            return result;
        }
    }
}

七 : 封装一个全局返回类ResponseResult ,以统一的格式返回数据到前端

package com.thingingcao.jpa.common;

import java.util.List;

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

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

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

	public ResponseResult(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;
	}
}

八 : 创建一个项目启动类DataJpaApplication

package com.thingingcao.jpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * <pre>
 * &#64;author cao_wencao
 * &#64;date 2018年12月20日 下午5:15:48
 * </pre>
 */
@SpringBootApplication
public class DataJpaApplication {

	/**
	 * <pre>
	 *   
	 * &#64;author cao_wencao
	 * &#64;param args
	 * </pre>
	 */
	public static void main(String[] args) {
		SpringApplication.run(DataJpaApplication.class, args);
	}

}

八 : 创建yml文件中配置链接的数据库springboot-data-jpa  ,然后启动项目测试

启动成功,根据我们实体类的注解,已经创建创出了表

 

测试添加一个学生:

 

修改一个学生数据:

 

 

根据id删除一条数据:

 

查询所有数据:

 

根据id查询一条数据:

 

根据姓名查询:

 

文章最后发布于: 2018-12-21 14:53:04
展开阅读全文
0 个人打赏
私信求帮助

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览