SpringBoot2.X基础教程:SpringBoot整合MyBatis附源码
Posted Java程序鱼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot2.X基础教程:SpringBoot整合MyBatis附源码相关的知识,希望对你有一定的参考价值。
微信号:hzy1014211086,如果你正在学习Spring Boot,可以加入我们的Spring技术交流群,共同成长
上篇文章我们介绍了 Spring Boot 对传统 JdbcTemplate 的集成,这篇文章我给大家介绍 Spring Boot 集成 MyBatis。这里分别介绍注解方式以及XML方式的整合。
一、准备数据表
CREATE TABLE `spring_boot`.`article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NULL COMMENT '文章标题',
`author` varchar(255) NULL COMMENT '作者',
PRIMARY KEY (`id`)
) COMMENT = '文章表';
二、添加依赖
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
大家要注意依赖版本兼容性
三、配置数据源
spring.datasource.url = jdbc:mysql://139.196.20.xxx:3306/spring_boot?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
四、编写领域对象
@Data
@NoArgsConstructor
public class Blog {
private Integer id;
private String title;
private String author;
}
五、注解配置方式
新增
@RestController
public class BlogController {
@Autowired
public BlogService blogService;
/**
* 新增一篇文章
*
* @param blog 文章实体类
* @return
*/
@PostMapping(value = "/create")
public Object create(@RequestBody Blog blog) {
if (StringUtils.isBlank(blog.getTitle())) {
return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章标题");
}
if (StringUtils.isBlank(blog.getAuthor())) {
return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章作者");
}
return blogService.create(blog);
}
}
@Service
public class BlogServiceImpl implements BlogService {
@Autowired
private BlogMapper blogMapper;
@Override
public Object create(Blog blog) {
int count = blogMapper.create(blog);
if (count > 0) {
return ResponseUtil.ok("插入成功");
} else {
return ResponseUtil.fail(ResultEnums.SERIOUS.getCode(), "插入失败");
}
}
}
@Mapper
public interface BlogMapper {
@Insert("INSERT INTO article(title, author) VALUES(#{title}, #{author})")
int create(Blog blog);
}
修改
@RestController
public class BlogController {
@Autowired
public BlogService blogService;
/**
* 通过id修改文章
*
* @param blog
* @return
*/
@PostMapping(value = "/updateById")
public Object updateById(@RequestBody Blog blog) {
if (StringUtils.isBlank(blog.getTitle())) {
return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章标题");
}
if (StringUtils.isBlank(blog.getAuthor())) {
return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章作者");
}
return blogService.updateById(blog);
}
}
@Service
public class BlogServiceImpl implements BlogService {
@Autowired
private BlogMapper blogMapper;
@Override
public Object updateById(Blog blog) {
int count = blogMapper.updateById(blog);
if (count > 0) {
return ResponseUtil.ok("修改成功");
} else {
return ResponseUtil.fail(ResultEnums.SERIOUS.getCode(), "修改失败");
}
}
}
@Mapper
public interface BlogMapper {
@Update("UPDATE article SET title=#{title},author=#{author} WHERE id=#{id}")
int updateById(Blog blog);
}
查询
@RestController
public class BlogController {
@Autowired
public BlogService blogService;
/**
* 查询所有文章
*
* @return
*/
@GetMapping(value = "/getAll")
public List<Blog> getAll() {
return blogService.getAll();
}
/**
* 通过标题查询文章
*
* @param title
* @return
*/
@GetMapping(value = "/getByTitle")
public Object getByTitle(String title) {
if (StringUtils.isBlank(title)) {
return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章标题");
}
return blogService.getByTitle(title);
}
}
@Service
public class BlogServiceImpl implements BlogService {
@Autowired
private BlogMapper blogMapper;
@Override
public List<Blog> getAll() {
return blogMapper.getAll();
}
@Override
public List<Blog> getByTitle(String title) {
return blogMapper.getByTitle(title);
}
}
@Mapper
public interface BlogMapper {
@Select("SELECT * FROM article")
@Results({
@Result(column = "id", property = "id", javaType = Integer.class),
@Result(property = "title", column = "title", javaType = String.class),
@Result(property = "author", column = "author", javaType = String.class)
})
List<Blog> getAll();
@Select("SELECT * FROM article WHERE title = #{title}")
@Results({
@Result(column = "id", property = "id", javaType = Integer.class),
@Result(property = "title", column = "title", javaType = String.class),
@Result(property = "author", column = "author", javaType = String.class)
})
List<Blog> getByTitle(String title);
}
删除
@RestController
public class BlogController {
@Autowired
public BlogService blogService;
/**
* 通过ID删除文章
*
* @param id
* @return
*/
@PostMapping(value = "/deleteById")
public Object deleteById(Integer id) {
if (null == id || 0 == id.longValue()) {
return ResponseUtil.fail(ResultEnums.BAD_ARGUMENT_VALUE.getCode(), "请输入文章id");
}
return blogService.deleteById(id);
}
}
@Service
public class BlogServiceImpl implements BlogService {
@Autowired
private BlogMapper blogMapper;
@Override
public Object deleteById(Integer id) {
int count = blogMapper.deleteById(id);
if (count > 0) {
return ResponseUtil.ok("删除成功");
} else {
return ResponseUtil.fail(ResultEnums.SERIOUS.getCode(), "删除失败");
}
}
}
@Mapper
public interface BlogMapper {
@Delete("DELETE FROM article WHERE id = #{id}")
int deleteById(Integer id);
}
六、XML配置方式
修改application.properties 配置文件
#指定bean所在包
mybatis.type-aliases-package=com.fish.chapter6.domain
#指定映射文件
mybatis.mapperLocations=classpath:mapper/*.xml
新增
@Mapper
public interface BlogMapper {
int create(Blog blog);
}
<insert id="create" parameterType="com.fish.chapter6.domain.Blog">
INSERT INTO article (title, author) VALUES (#{title}, #{author})
</insert>
修改
@Mapper
public interface BlogMapper {
int updateById(Blog blog);
}
<update id="updateById" parameterType="com.fish.chapter6.domain.Blog">
UPDATE article SET title = #{title}, author = #{author} WHERE id = #{id}
</update>
查询
@Mapper
public interface BlogMapper {
List<Blog> getAll();
List<Blog> getByTitle(@Param("title") String title);
}
<select id="getByTitle" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from article
<where>
<if test="title != null and title !=''">
AND title = #{title,jdbcType=VARCHAR}
</if>
</where>
</select>
<select id="getAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from article
</select>
删除
@Mapper
public interface BlogMapper {
int deleteById(@Param("id") Integer id);
}
<delete id="deleteById" parameterType="java.lang.Integer">
DELETE FROM article WHERE id = #{id}
</delete>
更多mybatis数据访问操作的使用请参考:MyBatis官方中文参考文档
彩蛋,很多小伙伴会发现一个问题,项目启动一段时间放那里不动,然后在访问接口时,就会报错,这和我们使用的数据源有关(Hikari),在后面《数据源详解》章节我会教大家如何解决。
七、源码
本文的相关例子可以查看下面仓库中的 chapter6 目录:
- Gitee:https://gitee.com/hezhiyuan007/spring-boot-study
- Github:https://github.com/java-fish-0907/spring-boot-study
以上是关于SpringBoot2.X基础教程:SpringBoot整合MyBatis附源码的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot2.X基础教程:SpringBoot整合MyBatis附源码
SpringBoot2.X最佳实践《一》 之 SpringBoot2.x初体验
SpringBoot2.x系列教程48--多数据源配置之AOP动态切换数据源