在大部分系统中,数据的读取、存储是很重要的一个步骤。数据库也多种多样,集成的方式也较多。推荐Spring Boot + MyBatis Plus的方式。省去很多很多步骤。

添加依赖

mybatis

1
2
3
4
5
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>

连接池

1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>

jdbc驱动

1
2
3
4
5
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

配置文件

数据库信息配置

1
2
3
4
5
6
7
8
9
10
11
spring:
application:
name: mysql-demo
## mybatis 集成
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/technotes?useUnicode=true&characterEncoding=utf8
url: ${spring.datasource.jdbc-url}
username: root
password: xxx

配置数据库mapper的包

1
2
3
4
5
6
7
@MapperScan(basePackages = {"com.technotes.mysqldemo.mybatis.dao"})
@SpringBootApplication
public class MysqlDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MysqlDemoApplication.class, args);
}
}

创建数据库表

举例创建一个简单的 student表

1
2
3
4
5
CREATE TABLE `t_student` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
`age` INT NULL,
PRIMARY KEY (`id`));

MyBatis Generator的使用

MyBatis generator 可以根据数据库表生成对应 model、mapper、service等,推荐使用。

主要代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123");
dsc.setUrl("jdbc:mysql://localhost:3306/technotes");
mpg.setDataSource(dsc);

// 策略配置
StrategyConfig strategy = new StrategyConfig();
// 表名生成策略
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setTablePrefix("t_");
// 需要生成的表
strategy.setInclude("t_student");
strategy.setSuperServiceClass(IService.class);
strategy.setSuperServiceImplClass(ServiceImpl.class);
strategy.setSuperMapperClass(null);

服务调用

controller编写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

//由mybatis generator生成
@Autowired
private IStudentService studentService;


@ResponseBody
@RequestMapping("/add")
public Student add(@RequestParam(required = false) String name, @RequestParam(required = false) Integer age) {
Student student = new Student();
student.setName(name);
student.setAge(age);

studentService.save(student);
return student;
}

调用

http://localhost:8080/student/add?name=name1&age=24

返回

1
2
3
4
5
{
"id": 2,
"name": "name1",
"age": 24
}

相关demo源码 见 Github