Spring连接Mysql的方式有很多,例如JDBC,Spring JPA,Hibeirnate,Mybatis等,本文主要介绍使用最简单、最底层的JDBC方式来连接Mysql数据库,JDBC连接数据库,主要是注入JdbcTemplate,使用JdbcTemplate来操作数据库。
建表语句如下:
CREATE TABLE `user` (
`id` varchar(20) DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
`age` varchar(20) DEFAULT NULL,
`sex` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `user`(`id`, `name`, `age`, `sex`) VALUES ('1', 'oyc', '18', 'male');
INSERT INTO `user`(`id`, `name`, `age`, `sex`) VALUES ('2', 'ouyang', '19', 'male');
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-jdbc
在resource文件夹下添加application.properties配置文件并输入数据库参数,如下:
############################################################
#
# mysql
#
############################################################
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
package com.oycbest.jdbcdemo.domain;
/**
* @author oyc
* @Description:用户实体类
* @date 2018/7/8 22:51
*/
public class User{
//用户id
private String id;
//用户名称
private String name;
//户年龄
private String age;
//用户性别
private String sex;
//此处省略setter和getter
}
/**
* @author oyc
* @Description: 用户控制类
* @date 2018/7/8 22:10
*/
@Controller
@RequestMapping("/jdbc")
public class JdbcController {
@Resource
private JdbcTemplate jdbcTemplate;
@RequestMapping("/user")
@ResponseBody
public List list(ModelMap map) {
String sql = "SELECT * FROM user";
List userList = jdbcTemplate.query(sql, new RowMapper() {
User user = null;
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
user = new User();
user.setId(rs.getString("id"));
user.setName(rs.getString("name"));
user.setSex(rs.getString("sex"));
user.setAge(rs.getString("age"));
return user;
}
});
for (User user : userList) {
System.out.println(user.toString());
}
return userList;
}
@RequestMapping("/userList")
public String userList(ModelMap map) {
String sql = "SELECT * FROM user";
List userList = jdbcTemplate.query(sql, new RowMapper() {
User user = null;
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
user = new User();
user.setId(rs.getString("id"));
user.setName(rs.getString("name"));
user.setSex(rs.getString("sex"));
user.setAge(rs.getString("age"));
return user;
}
});
map.addAttribute("users", userList);
return "user";
}
}
源代码地址:https://github.com/oycyqr/jdbcdemo/