Spring Boot 连接 MySQL 数据库 JPA

Spring Boot 是一个在 Spring 的基础上搭建的全新的微框架,简化了 Spring 的搭建和开发工程。Spring Boot 也得到很多大厂的支持,国外有 Pivotal 和 Netflix ,国内有很多企业都在使用,它在搭建微服务上得到更多的支持,版本迭代很快,前途一片光明。Spring Boot 的快速搭建真的太简单了,直接参考官网文档就可以了,我博客就不写搭建并运行 Hello World 了。我们直接来连接 MySQL 数据库,并使用前面文章《Spring MVC 连接 MySQL 数据库 JPA》提到的 JPA 来连接,如果对 JPA 还是不太了解的可以前往阅读。在本例子中 Spring Boot 跟 Spring MVC 最大的不同就是配置文件,实现功能逻辑的代码基本一样,还有 JSP 不是页面首选,官方默认使用 Thymeleaf 。大家可以去对比一下这两个项目的代码,领略一下 Spring Boot 的简约美。

创建项目

使用 maven 创建 maven-archetype-quickstart 为原型的项目 spring-boot-jpa 。

程序结构

目录说明:
DB:存放数据库文件 spring_boot_mysql.sql 现在只能手动创建数据表,后续会出自动创建数据表文章。

src/main/java/com.aidansu.springboot 目录
common:公共文件,用于存放一些常量,工具类
controller:控制层,处理用户输入请求
model:模型层,存放对象
repository:持久化层,提供数据表存取机制,主要是 ORM 框架实现以对象-关系数据库的映射
service:服务层,由表现层直接调用,用于处理事务
App:启动程序

resources 目录
static:存放静态文件,如图片,CSS 样式,js 文件
templates:模板文件,主要是 html 文件
application.properties:Spring Boot 自动加载的文件配置
application-dev.properties:开发环境的配置文件

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
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons.lang.version>2.6</commons.lang.version>
<gson.version>2.5</gson.version>
<junit>3.8.1</junit>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.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>
<!-- Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- MySQL 数据库连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- GSON -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

Spring Boot 配置

Spring Boot 会自动扫描classpath下的application.properties文件,如果有就加载文件配置
Spring Boot 中多环境配置文件名需要满足application-{profile}.properties的格式,{profile}对应你的环境标识

application-dev.properties:开发环境
application-test.properties:测试环境
application-prod.properties:生产环境

application.properties 文件设置多环境配置文件属性,有开发、测试、生产,我们这里设置成开发的环境 dev

1
spring.profiles.active=dev

application-dev.properties:开发环境的配置文件,开发环境的主要配置都写在这里。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 服务端口
server.port=8080
# session最大超时时间(分钟),默认为30
server.session-timeout=60
# 数据库连接
spring.datasource.initialize=true
spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_mysql?useUnicode=true&characterEncoding=utf-8&useSSL=true&autoReconnect=true
spring.datasource.username=root
spring.datasource.password=mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
# Thymeleaf设置
# set to false for hot refresh
spring.thymeleaf.cache=false

这样就配置完了,是不是很简单!

Model 类

给 User 类添加注解

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
@Entity
@Table(name="t_user")
public class User implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String telephone;
@Column(name="create_time")
private Date createTime;
@Column(name="last_login_time")
private Date lastLoginTime;
@Column(name="update_time")
private Date updateTime;
public User() {
}
public User(String username, String password, String telephone, Date createTime, Date lastLoginTime, Date updateTime) {
this.username = username;
this.password = password;
this.telephone = telephone;
this.createTime = createTime;
this.lastLoginTime = lastLoginTime;
this.updateTime = updateTime;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(Date lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}

repository 数据持久化层

在 com.aidansu.springboot.repository 包下创建 UserRepository 类

1
2
3
4
5
6
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
User findById(long id);
}

Service 业务层

UserServiceImpl 实现类改成如下:

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
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserRepository userRepository;
@Override
public void insert(User user) {
userRepository.save(user);
}
@Override
public void update(User user) {
userRepository.save(user);
}
@Override
public void delete(long id) {
User user = userRepository.findOne(id);
if (user != null){
userRepository.delete(user);
}
}
@Override
public User findById(long id) {
return userRepository.findById(id);
}
@Override
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
public List<User> findAll() {
return userRepository.findAll();
}
}

Controller 控制层

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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/**
* 用户登录 demo
*/
@Controller
public class UserController {
@Autowired
private UserService userService;
/**
* 主页面
*/
@RequestMapping(value="/" ,method = RequestMethod.GET)
public String index(){
return "index";
}
/**
* 跳转到用户登录页面
*/
@RequestMapping(value="/login" ,method = RequestMethod.GET)
public String login(){
return "login";
}
/**
* 跳转到用户注册页面
*/
@RequestMapping(value="/register" ,method = RequestMethod.GET)
public String register(){
return "register";
}
/**
* 用户注册
*
* @param request
*/
@RequestMapping(value="/registering" ,method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody
public String registering(HttpServletRequest request){
// 获取传递过来的参数
String username = request.getParameter("username");
String password = request.getParameter("password");
String password2 = request.getParameter("password2");
String telephone = request.getParameter("telephone");
if(StringUtil.isEmpty(username)) {
return ErrorResponseUtil.setResponse("400", "Username can not be null");
}
if(StringUtil.isEmpty(password)) {
return ErrorResponseUtil.setResponse("400", "Password can not be null");
}
if(StringUtil.isEmpty(password2)) {
return ErrorResponseUtil.setResponse("400", "Confirm password can not be null");
}
if(!password.equals(password2)){
return ErrorResponseUtil.setResponse("400", "Two passwords are inconsistent");
}
// 验证用户名是否已经注册过
User user ;
try {
user = userService.findByUsername(username);
}catch(Exception e){
user = null;
}
if(user != null){
return ErrorResponseUtil.setResponse("400", "The username is registered");
}
String shaPwd;
try {
shaPwd = EncryptUtil.encryptSHA(password) ;
} catch (NoSuchAlgorithmException e) {
return ErrorResponseUtil.setResponse("400", "The password can not be encrypted");
}
Date date = new Date();
User newUser = new User();
newUser.setUsername(username);
newUser.setPassword(shaPwd);
if(StringUtil.isNotEmpty(telephone)){
newUser.setTelephone(telephone);
}
newUser.setCreateTime(date);
newUser.setLastLoginTime(date);
newUser.setUpdateTime(date);
try {
userService.insert(newUser);
}catch(Exception e){
return ErrorResponseUtil.setResponse("400", e.getMessage());
}
return ErrorResponseUtil.setResponse("200", "registration success");
}
/**
* 用户登录
*/
@RequestMapping(value="/logining" ,method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody
public String logining(HttpServletRequest request){
// 获取传递过来的参数
String username = request.getParameter("username");
String password = request.getParameter("password");
if(StringUtil.isNotEmpty(username) && StringUtil.isNotEmpty(password) ){
User user;
try {
user = userService.findByUsername(username);
}catch (Exception e){
user = null;
}
if(user != null){
String shaPwd ;
try {
shaPwd = EncryptUtil.encryptSHA(password) ;
} catch (NoSuchAlgorithmException e) {
shaPwd = "" ;
}
if(StringUtil.isNotEmpty(user.getPassword()) && shaPwd.equals(user.getPassword())){
SessionUtil.login(user, request);
user.setLastLoginTime(user.getUpdateTime());
user.setUpdateTime(new Date());
try {
userService.update(user);
}catch(Exception e){
return ErrorResponseUtil.setResponse("400", e.getMessage());
}
return ErrorResponseUtil.setResponse("200", "login successful");
}else{
return ErrorResponseUtil.setResponse("400", "Password error");
}
}else{
return ErrorResponseUtil.setResponse("400", "The user can not be found");
}
}else{
return ErrorResponseUtil.setResponse("400", "param is null");
}
}
/**
* 跳转到用户列表
*/
@RequestMapping(value="/user-list" ,method = RequestMethod.GET)
public String userList(HttpServletRequest request, Model model){
if(!SessionUtil.isLogin(request))
return "redirect:login";
// 获取当前用户信息
User user = SessionUtil.getUserFromSession(request);
model.addAttribute("user",user);
List<User> userList = userService.findAll();
model.addAttribute("users",userList);
return "user-list";
}
/**
* 根据id删除用户
*/
@RequestMapping(value = "/delete", method = RequestMethod.GET)
public String goDelete(HttpServletRequest request) {
int id = Integer.valueOf(request.getParameter("id"));
userService.delete(id);
return "redirect:/user-list";
}
/**
* 登出
*/
@RequestMapping(value="/logout" ,method = RequestMethod.GET)
public String logout(HttpServletRequest request){
SessionUtil.logout(request);
return "redirect:login";
}
}

程序启动方法

App 类为程序启动类

1
2
3
4
5
6
7
8
9
@SpringBootApplication
public class App {
public static void main( String[] args ) {
System.out.println( "Hello World JPA !" );
// 启动 Spring Boot
SpringApplication.run(App.class, args);
}
}

要点:

  • @SpringBootApplication 注释申明了这个类,等价于三个注释 @Configuration @EnableAutoConfiguration @ComponentScan 。
  • main()方法中,SpringApplication.run() 引导项目启动。

Run

执行 App 类中的 main 方法,服务器就会启动在 http://localhost:8080 端口上。

本次项目 spring-boot-jpa 的项目代码已经放在 github 上,有需要的同学可以下载查看。地址: https://github.com/aidansu/spring-boot-jpa

想了解更多关于 Spring Boot 框架信息的可以查看官方网站:http://projects.spring.io/spring-boot/

完!

坚持原创技术分享,您的支持将鼓励我继续创作!