整合MyBatis
Spring整合MyBatis:
- SpringConfig
- 导入JdbcConfig
- 导入MyBatisConfig
- JDBCConfig
- 定义数据源(加载properties配置项:driver、url、username、password)
- MyBatisConfig
- 定义SqlSessionFactoryBean
- 定义映射配置
Spring Boot整合:
创建项目
New Module --> Spring Initializr --> Next --> SQL --> MyBatis Framework、MySQL Driver
package com.xxx.domain;
public class Book {
private Integer id;
private String name;
private String type;
private String description;
// ... getter setter toString
}
package com.xxx.dao;
@Mapper
public interface BookDao {
@Select("select * from tbl_boo where id = #{id}")
public Book getById(Integer id);
}
application.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db
username: root
password: root
SpringbootApplicationTests.java
class SpringbootApplicationTests {
@Autowired
private BookDao bookDao; // 解决报错,Inspections --> Severity (Error --> Warning)
@Test
void testGetById() {
Book book = bookDao.getById(1);
System.out.println(book);
}
}
使用druid数据源
pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
type: com.alibba.druid.pool.DruidDataDource
