步骤:
1、创建项目;
2、添加mybatis依赖;
3、在application.yml进行数据源属性配置;
4、定义数据源对象与配置文件中前缀是spring.datasource的配置进行绑定;
5、创建数据表(department,employee);
6、创建实体类;
7、创建mapper接口;
8、编写controller处理请求,调用mapper对象执行查询方法。
1.创建项目
项目结构:
2,添加Druid依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
application.yml
#端口号
server:
port: 8080
#数据源配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/myjdbc212?characterEncoding=utf-8&serverTimezone=UTC
username: root
password: 123456
#sql:
#init:
#指定脚本文件位置
#schema-locations: classpath:user.sql
#初始化方式
#mode: always
#设置数据源类型C
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
configuration:
map-underscore-to-camel-case: true
#mybatis:
#指定mybatis配置文件的位置
#config-location: classpath:mybatis/mybatis-config.xml
#指定映射文件的位置
mapper-locations: classpath:mybatis/mapper/*.xml
3,config包下
DruidConfig类
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DruidDataSource getDurid(){
return new DruidDataSource();
}
}
MyBatisConfig类
@Configuration
public class MyBatisConfig {
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
//下划线与驼峰命名进行自动映射
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
4,controller类
DepartmentController类:
@RestController
public class DepartmentController {
@Autowired
private DepartmentMapper departmentMapper;
//根据id查询部门
@RequestMapping("/dept/{id}")
public Department getDepById(&#