MyBatis是Java领域一个著名的O/R Mapping框架, 与Hibernate不同,MyBatis只是适度在JDBC之上增加了一个薄层,以简化数据库应用的开发。本文演示在 Spring Boot 中如何引用 MyBatis。
本文使用在 Spring Boot 构建Rest服务实验手册(一) 中使用的案例。只是使用MyBatis 代替了默认的 JPA 实现。
构建项目骨架
在Spring Boot Starter ,填写项目的基本配置信息和项目中需要用到的第三方组件,根据实验的目标,选择用 maven 作为构建工具,Java 作为编程语言,Spring Boot 的版本选择当前的稳定版本 2.1.6。 第三方包选择:Lombok, Spring Web Starter, H2 Database。
然后点击 “Generate the Project” 按钮,下载生成的项目基本包。
然后用 IDEA 打开项目目录, 因为有目录中有 pom.xml 文件存在,IDEA 能侦察到这是个 maven 项目,会自动下载依赖的第三方包。 (如果你是第一次构建 Spring Boot 项目,这个下载的过程可能比较长)
添加 MyBatis依赖
在 pom.xml 中添加如下依赖:
1 2 3 4 5
| <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
|
添加实体类与表结构
在源代码包中添加 model 包,并建立一个名为: Todo 的实体类,代码如下:
1 2 3 4 5 6 7 8 9 10
| @Data @NoArgsConstructor public class Todo {
private Integer id;
private String title;
private String description; }
|
在资源目录 src/main/resources 中添加文件 schema.sql, 内容如下:
1 2 3 4 5 6 7 8 9
| drop table todo;
create table todo ( id bigint auto_increment, title varchar(100) not null, description varchar(255) not null, primary key(id) );
|
再添加一个名为 data.sql 的文件,用来初始化数据, 内容如下;
1 2 3
| insert into todo (title, description) values ('tom', 'desc for tom');
insert into todo (title, description) values ('jack', 'desc for jack');
|
构建 Repository 类
建立 repository 包,在包中新建一个名为 TodoRepository 的类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @Repository @Mapper public interface TodoRepository {
@Select("SELECT * FROM todo WHERE id = #{id}") public Todo findById(Integer id);
@Select("SELECT * FROM todo") public List<Todo> findAll();
@Insert("INSERT INTO todo (title, description) values ( #{title}, #{description}") public int insert(Todo todo);
@Delete("DELETE FROM todo WHERE id = #{id}") public int delete(Integer id);
@Update("UPDATE todo SET title = #{title}, description = #{description} WHERE id = #{id}") public int update(Todo todo);
}
|
添加数据配置
在本实例中给,我们使用 h2 数据库,在 application.yml 中添加如下内容:
1 2 3 4 5 6 7 8 9 10 11 12
| spring: datasource: driverClassName: org.h2.Driver url: jdbc:h2:./hohistar-con-data username: sa password: h2: console: enabled: true path: /api/h2 settings: web-allow-others: true
|