Mybatis 是一款优秀的持久层框架,原名叫做IBatis ,2010年有ApacheSoftwareFounddation迁移至Google Code 更名为Mynatis ,在Spring boot 中,Mybatis 提供了一套自动化配置的方案,可以做到Mybatis 开箱即用。
pom 依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
在使用mybatis 的时候,需要创建 接口,在接口上添加 @Mapper 用于声明是mybatis
@Mapper
// @Mapper 映射mapper.xml 文件
public interface BookMapper {
int addBook(Book book);
int deleteBookById(Integer id);
int updateBookById(Book book);
Book getBookById(Integer id);
List<Book> getAllBooks();
}
但是如果使用这种方式,需要在每个接口上面都添加@Mapper ,还有一种简单的配置方式,在配置类上添加@MapperScan 注解
@ComponentScan("com.mybatis.mybatis.mapperInterface")// 用于声明,去当前包下扫描 当前接口为所有的mapper 接口
Mapper.xml 文件
<?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.mybatis.mybatis.mapperInterface.BookMapper">
<insert id="addBook" parameterType="com.mybatis.mybatis.entity.Book">
insert into book (name,author) values (#{name} ,#{author} )
</insert>
<delete id="deleteBookById" parameterType="int" >
delete from book where id=#{id}
</delete>
<update id="updateBookById" parameterType="com.mybatis.mybatis.entity.Book">
update book set name = #{name} ,author = #{author} where id=#{id}
</update>
<select id="getAllBooks" resultType="com.mybatis.mybatis.entity.Book">
select * from book
</select>
<select id="getBookById" resultType="com.mybatis.mybatis.entity.Book" parameterType="int">
select * from book where id =#{id}
</select>
</mapper>
Mybatis 的配置
spring.datasource.url= jdbc:mysql:///chapter05
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=root
server.port= 8081
mybatis.type-aliases-package=com.mybatis.mybatis.mapperInterface
mybatis.mapper-locations= classpath:mapper/*.xml
上面是简单的配置。