一、整合Mybatis
-
创建项目时勾选Mybatis技术,导入对应starter;
-
在配置文件中配置数据源信息;
-
mapper类添加@Mapper才能被识别。
1、创建新模块,选择需要的技术集:
2、在application.yml 中配置数据源参数:
# 配置数据源信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
username: root
password: mypassword
3、创建mapper接口:
不同于传统Mybatis,SpringBoot无法在applicationContext.xml中实例化mapper接口,而需要用@mapper 声明接口
@Mapper
public interface BookDao {
@Select("select * from boot_book where id = #{id}")
public Book getById(Integer id);
}
4、测试
@SpringBootTest
class MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void contextLoads() {
System.out.println(bookDao.getById(1));
}
}
二、整合Mybatis-Plus
-
手工添加MyBatis-Plus对应的starter;
-
配置数据源;
-
mapper接口继承BaseMapper简化开发;
-
需要使用的第三方技术无法通过勾选确定时,需要手工添加坐标。
1、创建新模块,但SpringBoot并没有提供官方的MP技术集:
2、故需要手动添加starter依赖 :
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
3、数据源参数与Mybatis相同;
4、创建mapper接口:
@Mapper
public interface BookDao extends BaseMapper<Book> {
}
5、测试:
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void contextLoads() {
System.out.println(bookDao.selectById(2));
}
}
三、整合Druid连接池
1、导入starter:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
2、配置数据源:
# 配置数据源信息
#spring:
# datasource:
# driver-class-name: com.mysql.cj.jdbc.Driver
# url: jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
# username: root
# password: mypassword
# type: com.alibaba.druid.pool.DruidDataSource
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
username: root
password: mypassword
其他相关
pojo:
@TableName("boot_book")
public class Book {
private Integer id;
private String type;
private String name;
private String description;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", type='" + type + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}