Spring Boot整合MyBatis操作过程

所属分类: 软件编程 / java 阅读数: 23
收藏 0 赞 0 分享

1.加入mybatis-spring-boot-stater的Maven依赖

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

2.配置数据源

在src/main/resource中,application.properties配置文件中,这里面添加了一些数据库连接的信息

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3.代码注入数据源

package com.example;

import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.DispatcherServlet;
import com.alibaba.druid.pool.DruidDataSource;
import com.example.Listener.IndexListener;
import com.example.filter.IndexFilter;
import com.example.servlet.MyServlet;
@SpringBootApplication
public class SpringBootSimpleApplication {
  @Autowired
  private Environment env;
  @Bean
  public DataSource dataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl(env.getProperty("spring.datasource.url"));
    dataSource.setUsername(env.getProperty("spring.datasource.username"));//用户名
    dataSource.setPassword(env.getProperty("spring.datasource.password"));//密码
    dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
    dataSource.setInitialSize(2);
    dataSource.setMaxActive(20);
    dataSource.setMinIdle(0);
    dataSource.setMaxWait(60000);
    dataSource.setValidationQuery("SELECT 1");
    dataSource.setTestOnBorrow(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setPoolPreparedStatements(false);
    return dataSource;
  }
  public static void main(String[] args) {
    SpringApplication.run(SpringBootSimpleApplication.class, args);
  }
}

4.增加MyBatis的配置

MyBatisConfig.java类:

package com.example.mybatis;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
@Configuration
//加上这个注解,使得支持事务
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
  @Autowired
  private DataSource dataSource;
  @Override
  public PlatformTransactionManager annotationDrivenTransactionManager() {
    return new DataSourceTransactionManager(dataSource);
  }
  @Bean(name = "sqlSessionFactory")
  public SqlSessionFactory sqlSessionFactoryBean() {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    try {
      return bean.getObject();
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
  @Bean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}

MyBatisMapperScannerConfig.java类:

package com.example.mybatis;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * 扫描mybatis的接口
 */
@Configuration
// 因为这个对象的扫描,需要在MyBatisConfig的后面注入,所以加上下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
  @Bean
  public MapperScannerConfigurer mapperScannerConfigurer() {
    MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    //获取之前注入的beanName为sqlSessionFactory的对象
    mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
    //指定xml配置文件的路径
    mapperScannerConfigurer.setBasePackage("com.example.mybatis.mapper");
    return mapperScannerConfigurer;
  }
}

5.mybatis接口配置,这里使用student表作为示例

使用@Mapper注解来标识一个接口为MyBatis的接口,MyBatis会自动寻找这个接口

package com.example.mybatis.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface StudentMapper {
  @Select("select * from student;")
  public List<Map<String,Object>> find();
  @Insert("insert into student(id,name,age,score_sum,score_avg) "+
      "values(#{id},'Jim',33,200,100)")
  public int insert(@Param("id")int id);
}

6.service业务层调用接口

package com.example.mybatis;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.mybatis.mapper.StudentMapper;
@Service
public class StuMybatisService {
  @Autowired
  private StudentMapper studentMapper;
  public List<Map<String,Object>> find(){
    return studentMapper.find();
  }
  public int insert(int id){
    return studentMapper.insert(id);
  }
}

7.controller控制层调用service业务层

package com.example.mybatis;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/stumybatis")
public class StuMybatisController {
  private static Logger logger = LogManager.getLogger(StuMybatisController.class);
  @Autowired
  private StuMybatisService stuMybatisService;
  @RequestMapping("/list")
  public List<Map<String,Object>> getStus(){
    logger.info("从数据库读取Student集合");
    return stuMybatisService.find();
  }
  @RequestMapping("/add")
  public void addStus(){
    logger.info("student表中插入数据");
    stuMybatisService.insert(2);
  }
}

最终启动程序,进行访问:

http://localhost:8080/stumybatis/list

返回结果:

[{"score_sum":180.0,"name":"张三","id":1,"age":25,"score_avg":90.0},{"score_sum":200.0,"name":"Jim","id":2,"age":33,"score_avg":100.0}]

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

更多精彩内容其他人还在看

Java数据类型的规则

这篇文章主要介绍了Java数据类型的规则的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Spring整合TimerTask实现定时任务调度

这篇文章主要介绍了Spring整合TimerTask实现定时任务调度的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

详解SpringMVC使用MultipartFile实现文件的上传

本篇文章主要介绍了SpringMVC使用MultipartFile实现文件的上传,本地的文件上传到资源服务器上,比较好的办法就是通过ftp上传。这里是结合SpringMVC+ftp的形式上传的,有兴趣的可以了解一下。
收藏 0 赞 0 分享

SpringMVC上传文件的三种实现方式

本篇文章主要介绍了SpringMVC上传文件的三种实现方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

微信公众帐号开发-自定义菜单的创建及菜单事件响应的实例

本篇文章主要介绍了微信公众帐号开发-自定义菜单的创建及菜单事件响应的实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
收藏 0 赞 0 分享

浅析Java中的继承与组合

本文将介绍组合和继承的概念及区别,并从多方面分析在写代码时如何进行选择。文中通过示例代码介绍的很详细,有需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

利用反射获取Java类中的静态变量名及变量值的简单实例

下面小编就为大家带来一篇利用反射获取Java类中的静态变量名及变量值的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

java启动线程的3种方式对比分析

这篇文章主要为大家对比分析了java启动线程的3种方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

SpringMVC上传和解析Excel方法

这篇文章主要介绍了SpringMVC上传和解析Excel方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

JAVA中String类与StringBuffer类的区别

这篇文章主要为大家详细介绍了JAVA中String类与StringBuffer类的区别,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多