Spring Boot整合MyBatis操作过程
作者:牛头人 发布时间:2022-08-02 13:50:22
标签:spring,boot,mybatis
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的操作过程网站的支持!
来源:http://www.cnblogs.com/web424/p/6756957.html
0
投稿
猜你喜欢
- 在Android/Java开发中,用来处理字符串常用的类有3种: String、StringBuilder、StringBuffer。它们的
- 小程序获取手机号,后端JAVA解密流程代码微信官方文档获取手机号流程地址,先看下最好方便理解下面步骤实现思路,步骤如下1.前端需先调用官方w
- 一、JAVA简要概述先说一下java之父,詹姆斯·高斯林这是一个爱喝咖啡而又强大的男人。再来看一下JAVA有多火在TIOBE排行榜上JAVA
- 我想,对于各位使用面向对象编程语言的程序员来说,“接口”这个名词一定不陌生,但是不知各位有没有这样的疑惑:接口有什么用途?它和抽象类有什么区
- 本文分为俩部分:第一部分介绍如何给Eclipse安装Spring Boot开发插件spring tool suite(简称STS);第二部分
- 前言: 上图的报错信息相信大部分程序员都遇到过,奇怪的是虽然代码报错,但丝毫不影响程序的正常执行,也就是虽然编译器 IDEA 报错
- JSR303 是一套 JavaBean 参数校验的标准1、pom导入依赖<dependency><groupId>o
- MyBatis缓存我们知道,频繁的数据库操作是非常耗费性能的(主要是因为对于DB而言,数据是持久化在磁盘中的,因此查询操作需要通过IO,IO
- 最近要做一个网站,要求实现验证码程序,经过不断调试,终于成功实现功能。一、验证码生成类生成验证码的话需要用到java的Graphics类库,
- 本文实例讲述了C#实现char字符数组与字符串相互转换的方法。分享给大家供大家参考,具体如下:一、字符串转换为字符数组char[] temp
- 一:hibernate-validator 基础1. 简介:通过使用注解Annotations 给类或者类的属性加上约束(constrain
- 动态表单的含义是不要手动定义,直接在配置文件中进行定义。1.手动进行定义<form-beans > <form-bean
- Ping pingSender = new Ping(); PingReply reply = pingSender.Send("
- 前言这篇博客学习下Mybatis操作中使用Redis做缓存。这里其实主要学习几个注解:@CachePut、@Cacheable、@Cache
- 自己写了一个Swap测试类,代码如下:swap不能交换原生数据类型以及字符串类型。public class Swap5{ public st
- 本文实例讲述了Java实现求解一元n次多项式的方法。分享给大家供大家参考,具体如下:项目需要做趋势预测,采用线性拟合、2阶曲线拟合和指数拟合
- 本文实例讲述了C#实现XML与实体类之间相互转换的方法。分享给大家供大家参考,具体如下:using System;using System.
- 前言 短时间提升自己最快的手段就是背面试题,最近总结了Java常用的面试题,分享给大家,希望大家都能圆梦大厂,加油,我命由我不由天
- springboot aop里的@Pointcut()的配置@Pointcut("execution(public * com.w
- 前言本文主要给大家介绍了关于java poi导入Excel通用工具类的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍