Spring Boot+Mybatis的整合过程

依赖配置

结合前面的内容,这里我们要嵌入数据库的操作,这里以操作MySQL为例整合Mybatis,首先需要在原来的基础上添加以下依赖

<!-- mybatis依赖 -->
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.1.1</version>
</dependency>

当然啦,只依赖mybatis是不够的还需要依赖jdbc驱动以及返回json数据的json库(格式化数据)

<!-- MySql驱动 -->
<dependency>
  <groupId>org.apache.tomcat</groupId>
  <artifactId>tomcat-jdbc</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.21</version>
</dependency>
<!--Json库的依赖 -->
  <dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.1.43</version>
</dependency>

应用配置

接着需要在application.properties中添加数据库配置

#JDBC配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/weibo?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

这里连接的数据库名叫weibo,其中表结构如下:

接下来就需要来具体的初始化MyBatis配置以及数据表的操作了,先看一下工程结构

编写配置类

数据库相关的DataSource,SqlSeesion配置,其中DataSourse的配置可以理解为解读application.properties中的jdbc相关配置然后初始化JDBC驱动的,SqlSeesion配置主要是针对Mybatis使用事务操作时的配置信息。

package com.example.demo.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
@EnableAutoConfiguration
@ComponentScan
@MapperScan("com.example.demo.mapper")
public class JdbcConfig {
  // DataSource配置
  @Bean
  @ConfigurationProperties(prefix = "spring.datasource")
  public DataSource dataSource() {
    return new org.apache.tomcat.jdbc.pool.DataSource();
  }
  // 提供SqlSeesion(数据库事务操作相关的配置)
  @Bean
  public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource());
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
    return sqlSessionFactoryBean.getObject();
  }
  @Bean
  public PlatformTransactionManager transactionManager() {
    return new DataSourceTransactionManager(dataSource());
  }
}

添加Pojo类

该类主要接收数据表中的数据,所以属性基本上跟数据表的属性一致

package com.example.demo.bean;
public class Diary {
  private int id;
  private String title;
  private String content;
  private String pubTime;
  private int userId;
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getTitle() {
    return title;
  }
  public void setTitle(String title) {
    this.title = title;
  }
  public String getContent() {
    return content;
  }
  public void setContent(String content) {
    this.content = content;
  }
  public String getPubTime() {
    return pubTime;
  }
  public void setPubTime(String pubTime) {
    this.pubTime = pubTime;
  }
  public int getUserId() {
    return userId;
  }
  public void setUserId(int userId) {
    this.userId = userId;
  }
  @Override
  public String toString() {
    return "Diary [id=" + id + ", title=" + title + ", content=" + content + ", pubTime=" + pubTime + ", userId="
        + userId + "]";
  }
}

添加数据表操作接口

该类描述了操作数据表的过程,SprintBoot在运行中会根据类上的@Mapper注解找到它,因此不能落下这个注解

package com.example.demo.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.example.demo.bean.Diary;
@Mapper
public interface DiaryMapper {
  @Select("select * from diary where _id = #{id}")
  public Diary getDiaryById(@Param("id")Integer id);
}

使用

package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.example.demo.bean.Diary;
import com.example.demo.mapper.DiaryMapper;
@RestController
public class DiaryMappingController {
  @Autowired
  DiaryMapper diaryMapper;
  @RequestMapping("/diary")
  public String getDiary(Integer id){
    Diary d = diaryMapper.getDiaryById(id);
    String json = JSON.toJSONString(d);
    return json;
  }
}

最后运行SpringBoot项目,然后在浏览器上输入网址:

http://localhost:8080/diary?id=2

这样即可看到结果

 

到此SpringBoot+Mybatis的整合就完成了

源码:https://github.com/huajianzh/spring/tree/master/springdemo

以上所述是小编给大家介绍的Spring Boot+Mybatis的整合过程,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对呐喊教程网站的支持!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。