准备工作 : 数据库建表 创建javaBean
1.实现注解版MyBatis
@Mapper
public interface DepartmentMapper {
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);
@Delete("delete from department where id=#{id}")
public int deleteDeptById(Integer id);
@Options(useGeneratedKeys = true,keyProperty = "id")//标明自增id
@Insert("insert into department (departmentName) values (#{departmentName})")
public int insertDept(Department department);
@Update("update department set departmentName=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}
测试Controller
@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;
@GetMapping("/dept/{id}")
public Department getDept(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
@GetMapping("/dept")
public Department insertDept(Department department) {
departmentMapper.insertDept(department);
return department;
}
}
插入:http://localhost:8080/dept?departmentName=business
查询:http://localhost:8080/dept/4
image.png
自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;
@Configuration
public class MybatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
///开启驼峰命名
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
使用MapperScan批量扫描
@MapperScan(value = "com.xxx.mapper")//mapper所在的目录文件夹
@SpringBootApplication
public class JdbcdemoApplication {
public static void main(String[] args) {
SpringApplication.run(JdbcdemoApplication.class, args);
}
}
2.配置文件版
mapper:
//@Mapper 或者 @MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {
public Employee getEmployeeById(Integer id);
public void insertEmp(Employee employee);
}
application.yml 或者application.properties里面指定全局配置文件和sql映射文件位置
mybatis:
config‐location: classpath:mybatis/mybatis‐config.xml 指定全局配置文件的位置
mapper‐locations: classpath:mybatis/mapper/*.xml 指定sql映射文件的位置
全局配置文件:mybatis‐config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--<settings>-->
<!--<setting name="mapUnderscoreToCamelCase" value="true"/>-->
<!--</settings>-->
</configuration>
指定sql映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ari.ss.jdbcdemo.mapper.EmployeeMapper">
<!--public Employee getEmployeeById(Integer id);-->
<!--public void insertEmp(Employee employee);-->
<select id="getEmployeeById" resultType="com.ari.ss.jdbcdemo.bean.Employee">
select * from employee where id = #{id}
</select>
<insert id="insertEmp">
insert into employee (lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{d_id})
</insert>
</mapper>
测试同注解版
更多配置见官方文档:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
网友评论