springboot集成mybatis做数据库操作

前言

为啥要用mybatis

  • mybatis作为一个优秀的orm框架,功能强大,却又很轻量,他不像hibernate那么重(使用hibernate是真的不需要写sql,只要你了解hql语言就好了)
  • 应用场景广,可定制化sql,完美兼容sql语句,实现sql的动态调整
  • 性能高,跟项目的耦合度低

代码撸起来

做到以下几步,springboot集成mybatis就搞定了

1 修改pom文件

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

这一步我们可以省略掉,因为第一天搭建项目,就已经添加好了

2 修改application.yml配置文件

spring:
  application:
    name: bootDemo #应用名称
  datasource:
    # 配置数据源类型
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/boot?serverTimezone=GMT%2B8
    username: root
    password: 123$%^
    # 初始化,最小,最大连接数
    initialSize: 3
    minidle: 3
    maxActive: 18
    # 获取数据库连接等待的超时时间
    maxWait: 60000
    # 配置多久进行一次检测,检测需要关闭的空闲连接 单位毫秒
    timeBetweenEvictionRunsMillis: 60000
    validationQuery: SELECT 1 FROM dual
    # 配置监控统计拦截的filters,去掉后,监控界面的sql无法统计
    #filters: stat,wall,log4j

#mybatis配置
mybatis:
  mapper-locations: classpath:sqlmapper/*.xml

数据源信息我们之前已经配置过了,只需要配置mapper文件的位置就好了

3 配置启动类

@SpringBootApplication
@MapperScan("com.zyu.boot.demo.mapper")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

在启动类上加@MapperScan注解,表示去指定的路径下加载所有的Mapper类,注入到Spring的容器中

4 新增配置类,配置数据源实例

  • 在config包下新建DataSourceConfig.java
package com.zyu.boot.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@Order(2)
public class DataSourceConfig {
	@Value("${mybatis.mapper-locations}")
	private String mapperLocations;

	/**
	 * 主库的数据源
	 * 
	 * @return
	 */
	@Bean(name = "dataSource")
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource dataSource() {
		return new DruidDataSource();
	}

	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactory cluster1SqlSessionFactory(@Qualifier("dataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		// 配置mapper文件位置
		sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));
		return sqlSessionFactoryBean.getObject();
	}
}

5 新建测试类

  • 修改pom文件,引入spring-test依赖
<!-- spring-test依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
  • 新建创建用户测试方法
package com.zyu.boot.demo;

import com.zyu.boot.demo.entity.User;
import com.zyu.boot.demo.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;

@SpringBootTest(classes = { DemoApplication.class })
@RunWith(SpringRunner.class)
public class UserTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void addUserTest(){
        User user = new User();
        user.setUserid("zyufocus");
        user.setName("zyu");
        user.setAge(18);
        user.setGender(false);
        user.setCreateDate(new Date());
        user.setRole("admin");

        int col = userMapper.insert(user);
        System.out.println(col);
    }
}

  • 执行结果
    代码添加用户
    数据库截图

结束语

到这里,springboot集成mybatis就搞定了,别忘了去git提交代码哦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值