总结一下自己使用springboot整合mybatis的过程,写了一个类似于后台注册的片段,很基础,日后可能有进阶版。
一、首先添加依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
二、建立Entity实体类和Mapper类
如图:
在resources文件夹下建立mybatis文件夹,文件夹下建立mapper文件夹,在其中 建立 *. xml文件,注意文件名与mapper包中的文件名保持一致。
实体类@Entity 开头 mapper包 @Mapper 开头,在主文件中还要加上
@MapperScan(“com.example.august.mapper”) (扫描这个包,可以写自己的)
三、配置文件
mybatis文件夹中添加mybatis-config.xml文件,内容如下,可根据需要自由更改:
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Copyright 2009-2012 The MyBatis Team Licensed under the Apache License,
Version 2.0 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
OR CONDITIONS OF ANY KIND, either express or implied. See the License for
the specific language governing permissions and limitations under the License. -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 这个配置使全局的映射器启用或禁用 缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 设置超时时间, 它决定驱动等待一个数据库响应的时间 -->
<setting name="defaultStatementTimeout" value="100" />
<setting name="jdbcTypeForNull" value="OTHER" />
</settings>
</configuration>
然后在mybatis文件夹下建立mapper文件夹存放.xml文件。做完这些之后,进入application.properties文件,添加
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.example.august.entity`
最后一个配置是实体类所在的位置,可以根据需要改成自己的。
四:Mybatis文件夹下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.example.august.mapper.BookDao">
<insert id="insert" parameterType="com.example.august.entity.Book">
insert into book(title, number, price)
values (#{title}, #{number}, #{price})
</insert>
</mapper>
其中 id 是mapper包中对应的方法名,parameterType 参数类型,还有resultType 返回值类型,可以继续深入发掘,例如传参方法等问题
最后就可以在service包中的类中初始化mapper包下的类并使用其中的方法了