springboot集成mysql很简单
maven配置
创建springboot时,选择这两个即可
生成的依赖
1
2
3
4
5
6
7
8
9
10
11
12 1 <dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-jdbc</artifactId>
4 </dependency>
5
6 <dependency>
7 <groupId>mysql</groupId>
8 <artifactId>mysql-connector-java</artifactId>
9 <scope>runtime</scope>
10 </dependency>
11
12
springboot 配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
创建数据库表和实体
1
2
3
4
5
6
7
8 1CREATE TABLE `admin` (
2 `id` varchar(10) NOT NULL,
3 `adminname` varchar(20) DEFAULT NULL,
4 `password` varchar(20) DEFAULT NULL,
5 PRIMARY KEY (`id`)
6) ENGINE=InnoDB DEFAULT CHARSET=utf8
7
8
1
2
3
4
5
6
7 1public class Admin {
2 private String id;
3 private String adminname;
4 private String password;
5}
6
7
测试类
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 1public class MySpringBootApplicationTest {
2 @Resource
3 private JdbcTemplate jdbcTemplate;
4
5 @Test
6 public void mySqlTest(){
7 String sql = "select id,adminname,password from admin";
8 List<Admin> adminList = (List<Admin>) jdbcTemplate.query(sql,new RowMapper<Admin>(){
9 @Override
10 public Admin mapRow(ResultSet rs,int rowNum) throws SQLException {
11 Admin admin = new Admin();
12 admin.setId(rs.getString("id"));
13 admin.setAdminname(rs.getString("adminname"));
14 admin.setPassword(rs.getString("password"));
15 return admin;
16 }
17 });
18 System.out.println("查询成功");
19 for (Admin ad: adminList
20 ) {
21 System.out.println("id:"+ad.getId()+"; name:"+ad.getAdminname()+"; pass:"+ad.getPassword());
22 }
23 }
24}
25
26
JdbcTemplate:是通过jdbc连接数据库的工具类
@Resource 自动注入,通过这个注解,可以实例化jdbcTemplate对象
@Autowired 与@Resource的区别