本例以Windows, JDK1.8, Spring Boot (1.5.4) 为基础,演示使用Spring Boot + Spring Data JPA + MySQL 实现常用的增删查改操作。

以学生实体为例,来完成如下操作:

  1. 添加学生对象
  2. 查询所有学生和指定学生
  3. 更新指定的学生
  4. 删除指定的学生

用到的技术和工具

  1. Spring Boot 1.5.4.RELEASE
  2. Maven 3.10
  3. Java 8
  4. IntelliJ IDEA

项目结构

Maven pom.xml

File : pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.devnp</groupId>
<artifactId>spring-boot-jpa-mysql-demo</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>

<name>spring-boot-demo Maven Webapp</name>
<url>http://maven.apache.org</url>


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

<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--my sql connection-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>
<!--test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

<build>
<finalName>spring-boot-jpa-mysql-demo</finalName>
<plugins>
<!-- Package as an executable jar/war -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Configure 配置

配置数据库的连接信息, 本来使用.yaml文件格式来完成配置.这种文件的语法更加强大,比.properties配置更加容易阅读和使用, Spring Boot 默认会查找application.yaml的文件.
指定当前环境使用的配置文件.
File : application.yaml

1
2
3
4
#application config
spring:
profiles:
active: dev

配上数据库连接信息,指定Server端口.
File : application-dev.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
server:
port: 7001

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8
username: root
password: "!qaz2wsx"
jpa:
hibernate:
ddl-auto: update
show-sql: true

Entity 实体

File : Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.devnp.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;

/**
* Created by duliu on 23/7/2017.
*/
@Entity
@Table(name = "boot_student")
public class Student implements Serializable{

@Id
@GeneratedValue
private long id ;

private String name ;

private Integer age ;

private Date birthDt ;

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 getBirthDt() {
return birthDt;
}

public void setBirthDt(Date birthDt) {
this.birthDt = birthDt;
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", birthDt=" + birthDt +
'}';
}
}

Repository 数据库操作

本例主要继承和使用Spring JPA的常用操作.
File : StudentRepository.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.devnp.repository;

import com.devnp.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
* Created by duliu on 23/7/2017.
*/
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

}

Service

File : StudentService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.devnp.service;

import com.devnp.entity.Student;
import com.devnp.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
* Created by duliu on 23/7/2017.
*/
@Service
public class StudentService {

@Autowired
private StudentRepository studentRepository ;

@Transactional
public void saveStudent(Student student){
studentRepository.save(student);
}

public List<Student> listStudent(){
return studentRepository.findAll();
}

public Student listStudent(Long id){
return studentRepository.findOne(id);
}

@Transactional
public void delStudent(Long id){
studentRepository.delete(id);
}

}

Controller 控制器

定义对学生的操作接口

File : StudentController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.devnp.controller;

import com.devnp.entity.Student;
import com.devnp.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
* Created by duliu on 23/7/2017.
*/
@Controller
@RequestMapping("/student")
public class StudentController {

@Autowired
private StudentService studentService ;

@RequestMapping("/addStudent")
@ResponseBody
public String addStudent(@RequestParam("name") String name, @RequestParam("age") Integer age, @RequestParam("birthDt")
@DateTimeFormat(pattern="yyyy-MM-dd") Date birthDt){
Student student = new Student();

student.setName(name);
student.setAge(age);
student.setBirthDt(birthDt);

studentService.saveStudent(student);

return "Add Success." ;
}

@RequestMapping({"/listStudent", "/listStudent/{id}"})
@ResponseBody
public List<Student> listStudent(@PathVariable(value = "id",required = false) Long id){
if(id == null)
return studentService.listStudent();
else{
Student student =studentService.listStudent(id);

return Arrays.asList(student);
}
}

@RequestMapping("/delStudent/{id}")
@ResponseBody
public String delStudent(@PathVariable(value = "id",required = true) Long id){
studentService.delStudent(id);

return "Delete Success." ;
}

@RequestMapping("/editStudent/{id}")
@ResponseBody
public String editStudent(@PathVariable(value = "id",required = true) Long id, @RequestParam("name") String name,
@RequestParam("age") Integer age, @RequestParam("birthDt") @DateTimeFormat(pattern="yyyy-MM-dd") Date birthDt){

Student student = studentService.listStudent(id);

student.setName(name);
student.setAge(age);
student.setBirthDt(birthDt);

studentService.saveStudent(student);

return "Updated Success." ;
}
}

Spring Boot

File : SpringBootDemoApplication.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.devnp;

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

/**
* Created by P1205972 on 23/7/2017.
*/
@SpringBootApplication
public class SpringBootDemoApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}

Test 测试

File : StudentControllerTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.devnp.controller;

import com.devnp.entity.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;
import java.util.List;

import static org.junit.Assert.*;

/**
* Created by duliu on 23/7/2017.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentControllerTest {

@Autowired
private StudentController studentController ;

@Test
public void addStudentTest(){

String str = studentController.addStudent("Lao Zhao", 29, new Date());
System.out.println(str);

List<Student> students = studentController.listStudent(null);

if (students != null &amp;&amp; !students.isEmpty()){
for (int i = 0; i < students.size(); i++) {
System.out.println(students.get(i));
}
}
}

@Test
public void listStudentTest(){
List<Student> students = studentController.listStudent(null);

if (students != null &amp;&amp; !students.isEmpty()){
for (int i = 0; i < students.size(); i++) {
System.out.println(students.get(i));
}
}

List<Student> students2 = studentController.listStudent(1L);

if (students2 != null &amp;&amp; !students2.isEmpty()){
for (int i = 0; i < students2.size(); i++) {
System.out.println(students2.get(i));
}
}
}

@Test
public void delStudent(){
String str = studentController.delStudent(1L);
System.out.println(str);
}

@Test
public void editStudent(){
List<Student> students = studentController.listStudent(2L);

if (students != null &amp;&amp; !students.isEmpty()){
for (int i = 0; i < students.size(); i++) {
System.out.println(students.get(i));
}
}
String str = studentController.editStudent(2L, "Cheng Long", 50, new Date());
System.out.println(str);

List<Student> students2 = studentController.listStudent(2L);

if (students2 != null &amp;&amp; !students2.isEmpty()){
for (int i = 0; i < students2.size(); i++) {
System.out.println(students2.get(i));
}
}
}

}

Code 代码下载

springboot-jpa-mysql-demo.zip