当前位置 博文首页 > blackball1998的博客:整合Mybatis
Mybatis是一款轻量级的ORM框架,他有灵活方便的特点,可以帮我们实现自定义的Sql语句,并且很方便地编写动态Sql,使用Spring Boot框架进行开发时也可以很轻松地整个Mybatis框架
使用Mybatis,首先需要引入Mybatis的启动器依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
之前如果使用Spring框架整合Mybatis,我们需要一个Mybatis的配置文件,现在我们只需要在Spring Boot的核心配置文件中配置Mybatis的配置就行了,如以下配置对应了此前Mybatis配置文件的几项配置
mybatis:
configuration:
cache-enabled: false #关闭一级缓存
lazy-loading-enabled: true #开启懒加载
map-underscore-to-camel-case: true #开启下划线和驼峰命名自动转换
type-aliases-package: com.blackball.entity #配置需要别名的实体类包扫描
我有一个测试用的数据表,里面有一些数据
数据表对应的实体类如下
@Data
public class User {
private Integer id;
private Integer age;
private String name;
private String address;
}
测试使用Mybatis编写Sql将数据表中的数据查出来
使用Mybatis编写Sql语句有两种方法,一种是通过映射文件的方式,一种是通过注解的方式
使用Sql映射文件,首先定义一个Mapper接口,然后在接口上标注@Mapper
注解
@Mapper
public interface UserMapper {
List<User> queryUsers();
}
在类路径下编写一个Sql映射文件,绑定Mapper接口和接口中的方法
<?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.blackball.mapper.UserMapper">
<select id="queryUsers" resultType="com.blackball.entity.User">
select * from user
</select>
</mapper>
然后在配置文件中配置映射文件的包扫描路径
mybatis:
mapper-locations: classpath:mapper/*.xml
这样就可以使用Mapper接口操作数据库了
@SpringBootTest
class SpringDemoApplicationTests {
@Autowired
UserMapper userMapper;
@Test
void contextLoads() {
List<User> users = userMapper.queryUsers();
users.forEach(System.out::println);
}
}
测试结果
如果觉得在每个Mapper接口都标注@Mapper
注解太麻烦,可以使用@MapperScan
注解来扫描Mapper接口所在的包下的所有Mapper接口,可以配置在配置类上或者主启动类上
@SpringBootApplication
@MapperScan("com.blackball.mapper")
public class SpringDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDemoApplication.class, args);
}
}
这么做会引起idea编译器报错,不过不影响正常运行
要消除这个报错,可以在Mapper接口上标注@Repository
注解
我们也可以使用注解的方式将Mapper接口中的方法和Sql语句绑定
对于增删改查语句,对应的有@Select
@Update
@Delete
@Insert
四种注解,将这些注解标注在方法上,在注解中编写Sql语句
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User queryUser(int id);
}
除此之外还有一个@Options
注解,用于配置Sql语句
使用注解的方式,无需任何xml文件,也无需在配置文件中指定映射文件的包扫描路径,但是维护较为困难,一般简单的Sql语句使用注解的方式,复杂的使用编写映射文件的方式