注解的好处:
①不需要专门书写mapper的xml文件,直接在接口的方法上书写SQL语句,因此也不用配置xxxmapper.xml文件的地址
②注解的方式,不需要为实体类配置别名
1.搭建项目,导入web、jdbc、Mybatis、MySQL依赖
2.在配置文件中配置数据源datasource相关属性
spring:
datasource:
username: root
password: admin
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
(可以将默认的jdbc连接池更改为Druid连接池并配置相关属性)
详情参考配置Druid数据源
3.建立数据库和数据表
4.创建与表对应的bean类(department类,有id和departmentName属性)
5.创建mapper接口,在接口上加上mapper注解
如果mapper比较多,可以批量扫描,【 在主配置类上加@Mapper(value="mapper接口所在包") 】
@Mapper
public interface DepartmentMapper {
@Select("select * from mybatis.department where id = #{id}")
public Department getDeptById(Integer id);
@Delete("delete from mybatis.department where id = #{id}")
public int deleteDeptById(Integer id);
@Insert("insert into mybatis.department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
@Update("update department set departmentName=#{departmentName} where id = #{id}")
public int updateDept(Department department);
}
6.创建三层结构逐层调用(这里简化一下,直接controller调用mapper)
@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;
//根据部门id查询部门
@GetMapping("dept/{id}")
public Department getDeptById(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
//增加部门
@GetMapping("dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}
//删除部门
@GetMapping("dept/{id}")
public int deleteDeptById(@PathVariable("id") Integer id){
return departmentMapper.deleteDeptById(id);
}
//修改部门
@GetMapping("dept")
public Department updateDept(Department department){
departmentMapper.updateDept(department);
return department;
}
}
扩展一下(自定义Mybatis配置规则)
如果数据库中的字段名是department_name,而bean类的字段名是departmentName,这种时候可以添加一个配置类配置一下mybatis开启驼峰命名法映射规则,设置configuration.setMapUnderscoreToCamelCase(true);
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}