关于MyBatis,大部分人都很熟悉。MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。这篇文章主要介绍了Spring Boot集成MyBatis的两种方式(注解和XML文件配置),需要的朋友可以参考下.
1、使用XML配置MyBatis
1.1 在pom.xml文件中引入MyBatis的依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
1.2 编写MyBatis的主配置文件Mybatis-config.xml
在src/main/resources目录下新建mybatis文件夹,然后新建Mybatis-config.xml
文件并配置如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--一些有关于mybatis运行时行为的设置-->
<settings>
<!--开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
<!--开启懒加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--aggressvieLazyLoading当这个参数为true的时候,对任意延迟属性都会完全的加载,当为false时会按需加载-->
<setting name="aggressiveLazyLoading" value="false"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="true"/>
<!--开启自动映射-->
<setting name="autoMappingBehavior" value="PARTIAL"/>
<!--开启驼峰-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,
hashCode,toString"/>
</settings>
</configuration>
1.3 编写Mapper接口以及对应的Mapper映射文件
在src/main/java下新建mapper包,然后新建ArticleMapper
接口如下:
/**
*对article表的CRUD
*/
@Repository
@Mapper //特别注意一定要加上@Mapper注解(或者也可以在启动类中使用@MapperScan)
public interface ArticleMapper {
/**
* 增加一片文章
*
* @param article 文章对象
* @return
*/
Integer add(Article article) throws SQLException;
/**
* 删除一片文章
*
* @param id 文章id
* @return
*/
boolean delete(Integer id) throws SQLException;
/**
* 修改一片文章
*
* @param id
* @return
* @throws SQLException
*/
boolean update(@Param("id") Integer id, @Param("article") Article article) throws SQLException;
/**
* 根据传入的参数查询文章
*
* @param id
* @return
* @throws SQLException
*/
List<Article> getArticle(@Param("id") Integer id, @Param("title") String title) throws SQLException;
/**
* 查询所有的文章
*
* @return
* @throws SQLException
*/
List<Article> getAll() throws SQLException;
}
在src/main.resoures下新建mapper文件夹,然后在mapper文件夹中新建对应的Mapper映射文件ArticleMapper.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.xust.iot.springboot_db.mapper.ArticleMapper">
<insert id="add" parameterType="com.xust.iot.springboot_db.bean.Article" useGeneratedKeys="true" keyProperty="id">
INSERT INTO article ( title, summary, content,level, ctimes, picture )
VALUES
(#{title},#{summary},#{content},#{level},#{ctimes},#{picture})
</insert>
<delete id="delete" parameterType="integer">
delete from article where id=#{id}
</delete>
<update id="update">
update article
<if test="article!=null">
<set>
<if test="article.title!=null">title=#{article.title}</if>
<if test="article.summary!=null">summary=#{article.summary}</if>
<if test="article.content!=null">content=#{article.content}</if>
<if test="article.level!=null">level=#{article.level}</if>
<if test="article.ctimes!=null">ctime=#{article.times}</if>
<if test="article.picture!=null">picture=#{article.picture}</if>
</set>
</if>
<where>
id=#{id}
</where>
</update>
<select id="getArticle" resultType="com.xust.iot.springboot_db.bean.Article">
select * from article
<where>
<choose>
<when test="id!=null">id=#{id}</when>
</choose>
<choose>
<when test="title!=null">title=#{title}</when>
</choose>
</where>
</select>
<select id="getAll" resultType="com.xust.iot.springboot_db.bean.Article">
select * from article
</select>
</mapper>
然后在application.yml文件中配置mybatis这两个文件的位置:
mybatis:
config-location: classpath:/mybatis/mybatis-config.xml #MyBatis主配置文件的位置
mapper-locations: classpath:/mybatis/mapper/*.xml #mapper文件的位置 这种写法就注册了所有mapper包下的mapper映射文件
编写一个controller,简单测试一下看看我们配置的MyBatis能不能用。这里为了简单就没有写对应的service。
@Controller
public class ArticleController {
@Autowired
ArticleMapper articleMapper;
@ResponseBody
@RequestMapping("/article/{id}")
public List<Article> getArticle(@PathVariable("id") Integer id) {
List<Article> articles=articleMapper.getArticle(id,null);
//articles.forEach(article -> System.out.println("article"+article));
return articles;
}
}
测试结果:

2、使用注解配置MyBatis
MyBatis提供了以下几个CRUD基本注解: * @Select * @Update * @Insert * @Delete
增删改查占据了绝大部分的业务操作,掌握这些基础注解的使用还是很有必要的,例如下面这段代码无需XML即可完成数据查询:
@Repository
public interface CourseMapper {
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into course(cid,cname) values(#{cid},#(cname))")
int add(Course course);
@Delete("delete from course where id=#{id}")
boolean delete(Integer id);
@Update("update course set cid=#{course.cid},cname=#{course.cname}")
boolean update(@Param("id") Integer id, @Param("course") Course course);
@Select("select * from course where id=#{id}")
Course getOne(Integer id);
@Select("select * from course")
List<Course> getAll();
}
MyBatis提供的映射注解:
- @Results 用于填写结果集的多个字段的映射关系.
- @Result 用于填写结果集的单个字段的映射关系.
- @ResultMap 根据ID关联XML里面
.
@Results({
@Result(property = "userId", column = "USER_ID"),
@Result(property = "username", column = "USERNAME"),
@Result(property = "password", column = "PASSWORD"),
@Result(property = "mobileNum", column = "PHONE_NUM")
})
@Select("select * from t_user")
List<User> list();
在启动类上使用@MapperScan
扫描mapper包下的所有的Mapper接口,这样做的好处是可以省去在每个Mapper接口上写@Mapper
注解。
@MapperScan(value = "com.xust.iot.springboot_db.mapper")
@SpringBootApplication
public class SpringbootDbApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDbApplication.class, args);
}
}
还可以写一个配置类彻底取代MyBatis的所有XML文件。MyBatisConfig.java
@Configuration
public class MybatisConfig {
/**
* @return
*/
public ConfigurationCustomizer configurationCustomizern(){
return configuration -> {
configuration.setMapUnderscoreToCamelCase(true); //开启驼峰命名
configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
configuration.setCacheEnabled(true);
//.....在mybatis主配置文件可以设置的在这里都可以设置
};
}
}
编写一个controller,看看实际的效果:
@Controller
public class CourseController {
@Autowired
CourseMapper courseMapper;
@ResponseBody
@RequestMapping(value = "/course")
public List<Course> show(){
List<Course> courses = courseMapper.getAll();
courses.forEach(course -> System.out.println("course;"+course));
return courses;
}
}
测试结果:
