MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
本文将简单的演示在Spring Boot使用Mybatis的两种方式:使用注解的方式、使用XML配置的方式。
一、使用注解方式使用Mybatis
所谓无配置注解指的是不使用xml配置,所有和Mybatis相关的映射都使用注解来完成(包括Mapper扫描、查询结果与entity的映射等)。
1.1 在pom.xml文件中添加必要依赖如下
<dependencies>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>org.springframework.boot<groupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
在所添加的依赖中,我们简单解说一下mybatis-spring-boot-starter,mybatis-spring-boot-starter可以帮助你在Spring Boot中快速构建Mybatis应用,在Spring Boot中使用此starter有如下好处:
减少代码模板(几乎不需要);
减少XML配置;
自动检测存在的DataSource;
自动使用SqlSessionFactoryBean传递DataSource作为一个输入创建和注册一个SqlSessionFactory实例;
自动使用SqlSessionFactory创建和注册一个SqlSessionTemplate实例;
自动扫描mapper,连接这些mapper和SqlSessionTemplate并注册mapper到spring上下文,这样一来这些mapper就可以被注入为您的bean。
1.2 application.properties配置
mybatis.type-aliases-package=com.learnspringboot.mybatis.entity
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ron_intelligence_system?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=true&allowMultiQueries=true&serverTimezone=Asia/Hong_Kong
spring.datasource.username=root
spring.datasource.password=111111
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.testWhileIdle=true
spring.datasource.timeBetweenEvictionRunsMillis=60001
springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,然而这些过程你都不用管,这些都是自动完成的,直接拿起来使用就行了。
在启动类中添加对mapper包扫描@MapperScan
@SpringBootApplication
@MapperScan("com.learnspringboot.mybatis.mapper")
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
或者直接在Mapper类上面添加注解@Mapper,建议使用上面那种,不然每个mapper加个注解也挺麻烦的。
1.3 开发Mapper
public interface BlogTypeMapper {
@Select("select * from blog_type")
@Results({
@Result(property = "id",column = "id"),
@Result(property = "btId",column = "bt_id"),
@Result(property = "typeTxt",column = "type_txt"),
@Result(property = "userId",column = "user_id"),
@Result(property = "crtTime",column = "crt_time")
})
List getAll();
@Select("select * from blog_type where bt_id=#{btId}")
@Results({
@Result(property = "id",column = "id"),
@Result(property = "btId",column = "bt_id"),
@Result(property = "typeTxt",column = "type_txt"),
@Result(property = "userId",column = "user_id"),
@Result(property = "crtTime",column = "crt_time")
})
BlogType getOne(String btId);
@Insert("insert into blog_type(bt_id,type_txt,user_id,crt_time) values(#{btId},#{typeTxt},#{userId},#{crtTime})")
void insert(BlogType type);
@Update("update blog_type set type_txt=#{typeTxt},user_id=#{userId},crt_time=#{crtTime} where bt_id=#{btId}")
void update(BlogType type);
@Delete("delete from blog_type where bt_id=#{btId}")
void delete(String btId);
}
@Select 是查询类的注解,所有的查询均使用这个
@Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。
@Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
@Update 负责修改,也可以直接传入对象
@Delete 负责删除
1.4 使用
第三步基本上完成了Dao的开发,在需要使用的地方使用@Autowired注解基本就可使用,我们使用单元测试进行测试。
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisApplicationTests {
@Autowired
private BlogTypeMapper blogTypeMapper;
@Test
public void testInsert() {
System.out.println("----------测试插入------");
BlogType type=new BlogType();
type.setBtId("455550e8ba444f8aabdd696a0976a6bc");
type.setTypeTxt("Spring Boot MyBatis 实例讲解");
type.setUserId("80bda1819d4a4619b44750bfc3013183");
type.setCrtTime(new Date());
blogTypeMapper.insert(type);
type.setBtId("455550e8ba444f8aabdd696a0976a6ba");
type.setTypeTxt("Spring Boot系列");
blogTypeMapper.insert(type);
type.setBtId("455550e8ba444f8aabdd696a0976a6bb");
type.setTypeTxt("Spring Boot系列哈哈哈");
blogTypeMapper.insert(type);
testQuery();
}
@Test
public void testUpdate(){
System.out.println("----------测试更新------");
BlogType type=blogTypeMapper.getOne("455550e8ba444f8aabdd696a0976a6bb");
type.setTypeTxt("学习Spring Boot Mybatis");
blogTypeMapper.update(type);
type = blogTypeMapper.getOne("455550e8ba444f8aabdd696a0976a6bb");
System.out.println(type.getBtId()+"------>"+type.getTypeTxt());
}
@Test
public void testQuery(){
List list=blogTypeMapper.getAll();
System.out.println("----------查询数据------");
list.stream().forEach(item->{
System.out.println(item.getBtId()+"------>"+item.getTypeTxt());
});
}
@Test
public void testDelete(){
System.out.println("----------测试删除------");
blogTypeMapper.delete("455550e8ba444f8aabdd696a0976a6bb");
testQuery();
}
}
二、使用XML配置的方式使用Mybatis
pom文件配置与上面所描述的一致,这里不再赘述。只是使用XML配置的方式,我们需要在配置文件中增加实体类映射xml文件的配置路径以及Mybatis基础配置文件的路径。在application.properties新增以下配置:
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
2.1 mybatis-config.xml 配置(实例以最简单的模式演示)
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
typeAliases>
configuration>
2.2 添加BlogType映射文件
<mapper namespace="com.learningspringboot.mybatisxml.mapper.BlogTypeMapper" >
<resultMap id="BaseResultMap" type="com.learningspringboot.mybatisxml.entity.BlogType" >
<id column="id" property="id" />
<id column="bt_id" property="btId" />
<result column="type_txt" property="typeTxt" />
<result column="user_id" property="userId" />
<result column="crt_time" property="crtTime" />
resultMap>
<sql id="Base_Column_List" >
id, bt_id, type_txt, user_id, crt_time
sql>
<select id="getOne" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from blog_type
where bt_id = #{btId}
select>
<select id="getAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from blog_type
select>
<delete id="delete" parameterType="java.lang.String" >
delete from blog_type
where bt_id = #{btId}
delete>
<insert id="insert" parameterType="com.learningspringboot.mybatisxml.entity.BlogType" >
insert into blog_type (id, bt_id, type_txt, user_id, crt_time)
values (#{id}, #{btId}, #{typeTxt}, #{userId}, #{crtTime})
insert>
<update id="update" parameterType="com.learningspringboot.mybatisxml.entity.BlogType" >
update blog_type
set type_txt = #{typeTxt},
user_id = #{userId},
crt_time = #{crtTime}
where bt_id = #{btId}
update>
mapper>
2.3 编写Dao层代码
public interface BlogTypeMapper {
List getAll();
BlogType getOne(String btId);
void insert(BlogType type);
void update(BlogType type);
void delete(String btId);
}
2.4 使用
使用方法与基于注解的方式一致,这里不追溯。