spring boot前传(三):整合mybatis

本文详细介绍如何将MyBatis与Spring进行整合,并提供了一种传统整合方式的完整示例代码,包括pom.xml配置、实体映射文件、核心配置文件、DAO层代码等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        Mybatis和Spring Boot的整合有两种方式:

第一种:使用mybatis官方提供的Spring Boot整合包实现,

              地址:https://github.com/mybatis/spring-boot-starter

 

第二种:使用mybatis-spring整合的方式,也就是我们传统的方式
这里我们推荐使用第二种,因为这样我们可以很方便的控制Mybatis的各种配置问题,因为很多时候我们需要在里面配置缓存啊,别名啊,插件啊,所以第二种方式要灵活很多。

 

 

好了,废话不多说,直接上代码,注释在代码中是最容易理解的。

环境:spring4.3.9  +  mybatis3.2.8

这里我们以查询所有用户为例:

工程结构图:

pom文件

=========================pom.xml===========================

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.wx</groupId>
  <artifactId>bootpre03</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.3.9.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>4.3.9.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.9.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>4.3.9.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.3.9.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
		<!-- 阿里巴巴druid数据源 -->
	    <groupId>com.alibaba</groupId>
		    <artifactId>druid</artifactId>
		    <version>1.0.9</version>
		</dependency>
		<dependency>
	    	<groupId>mysql</groupId>
	    	<artifactId>mysql-connector-java</artifactId>
	    	<version>5.1.26</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.8</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<!-- 资源文件拷贝插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- java编译插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>

	</build>
</project>

用户实体映射文件

 

===============UserMapper.xml=====================

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"mybatis-mapper.dtd">
<mapper namespace="userentity">
	
	
	<select id="queryAll"  resultType="userEntity">
		SELECT * FROM users 
	</select>
</mapper>

mybatis核心配置文件

 

=======================mybatis-config.xml=================

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
	PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
	"mybatis-3-config.dtd">
<configuration>
<!-- 别名配置 -->
<typeAliases>
	<typeAlias type="com.wx.entitys.UserEntity" alias="userEntity"/>
	
</typeAliases>

</configuration>


dao层代码

 

====================UserDaoImpl.java==================

 

package com.wx.dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wx.entitys.UserEntity;

@Component("userDao")
public class UserDaoImpl implements IUserDao {
	@Autowired
	private SqlSessionTemplate sqlTemplate;
	
	public List<UserEntity> queryUserList(){
        List<UserEntity> userList = sqlTemplate.selectList("userentity.queryAll");
        return userList;
    }
}

业务层代码

 

===================UserBiz.java======================

 

package com.wx.biz;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.wx.dao.IUserDao;
import com.wx.entitys.UserEntity;

@Service
public class UserBiz {
	//Autowired默认根据类型进行装配,Qualifier根据名称装配
	@Autowired
	@Qualifier("userDao")
	private IUserDao userDao;
	
	public List<UserEntity> queryUserList(){
		return userDao.queryUserList();
	}
}

 

配置代码

数据源的配置

==============DataSourceConfig.java======================

 

package com.wx.configs;

import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@PropertySource(value = { "classpath:druidConfig.properties",
"classpath:jdbc.properties" }, ignoreResourceNotFound = true)
public class DataSourceConfig {
	@Value("${driverClassName}")
	private String driverClassName;
	@Value("${url}")
	private String url;
	@Value("${duridUserName}")
	private String username;
	@Value("${password}")
	private String password;
	@Value("${filters}")
	private String filters;
	@Value("${initialSize}")
	private int initialSize;
	@Value("${maxActive}")
	private int maxActive;
	@Value("${minIdle}")
	private int minIdle;
	@Value("${maxWait}")
	private int maxWait;
	@Value("${validationQuery}")
	private String validationQuery;
	@Value("${testWhileIdle}")
	private boolean testWhileIdle;
	@Value("${testOnBorrow}")
	private boolean testOnBorrow;
	@Value("${testOnReturn}")
	private boolean testOnReturn;
	@Value("${maxPoolPreparedStatementPerConnectionSize}")
	private int maxPoolPreparedStatementPerConnectionSize;
	@Value("${removeAbandoned}")
	private boolean removeAbandoned;
	@Value("${removeAbandonedTimeout}")
	private int removeAbandonedTimeout;
	@Value("${timeBetweenEvictionRunsMillis}")
	private int timeBetweenEvictionRunsMillis;
	@Value("${minEvictableIdleTimeMillis}")
	private int minEvictableIdleTimeMillis;
	
	@Bean(initMethod="init",destroyMethod="close")
	public DruidDataSource dataSource(){
		DruidDataSource dataSource=new DruidDataSource();
		try {
			dataSource.setUrl(url);
			dataSource.setDriverClassName(driverClassName);
			dataSource.setUsername(username);
			dataSource.setPassword(password);
			dataSource.setFilters(filters);
			dataSource.setInitialSize(initialSize);
			dataSource.setMaxActive(maxActive);
			dataSource.setMinIdle(minIdle);
			dataSource.setMaxWait(maxWait);
			dataSource.setValidationQuery(validationQuery);
			dataSource.setTestWhileIdle(testWhileIdle);
			dataSource.setTestOnBorrow(testOnBorrow);
			dataSource.setTestOnReturn(testOnReturn);
			dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
			dataSource.setRemoveAbandoned(removeAbandoned);
			dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
			dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
			dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
			System.out.println("数据源启动成功");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return dataSource;
	}
}

mybatis整合配置

 

=========================SpringConfig.java=====================

 

package com.wx.configs;

import java.io.IOException;
import java.sql.SQLException;

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.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;
import com.wx.dao.IUserDao;
import com.wx.dao.UserDaoImpl;

//通过该注解来表明该类是一个Spring的配置,相当于一个传统的ApplicationContext.xml
@Configuration
// 相当于配置文件里面的<context:component-scan/>标签
@ComponentScan(basePackages = "com.wx.configs,com.wx.dao,com.wx.biz")
public class SpringConfig {
	//dataSource对象会由spring容器自动注入
	@Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 设置mybatis的主配置文件
        ResourcePatternResolver resolver = 
        		new PathMatchingResourcePatternResolver();
        Resource mybatisConfigXml = resolver.getResource("classpath:mybatis-config.xml");
        sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
        //扫描mapper文件
        Resource[] resoures = null;
        try {
			resoures=resolver.getResources("classpath:com/wx/entitys/*.xml");
		} catch (IOException e) {
			e.printStackTrace();
		}
        sqlSessionFactoryBean.setMapperLocations(resoures);
        return sqlSessionFactoryBean.getObject();
    }
	
	//sqlSessionFactory对象会由spring容器自动注入
	@Bean
	public SqlSessionTemplate sqlTemplate(SqlSessionFactory sqlSessionFactory){
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}

 

 

 

数据源的注入方式如果不理解的话也可以这样写

 

package com.wx.configs;

import java.io.IOException;
import java.sql.SQLException;

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.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;
import com.wx.dao.IUserDao;
import com.wx.dao.UserDaoImpl;

//通过该注解来表明该类是一个Spring的配置,相当于一个传统的ApplicationContext.xml
@Configuration
// 相当于配置文件里面的<context:component-scan/>标签
@ComponentScan(basePackages = "com.wx.configs,com.wx.dao,com.wx.biz")
public class SpringConfig {
	@Autowired
	private DataSource dataSource;
	
	@Autowired
	SqlSessionFactory sqlSessionFactory;
	@Bean
	public SqlSessionFactoryBean sqlSessionFactory() {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		// 设置数据源
		sqlSessionFactoryBean.setDataSource(dataSource);
		// 设置mybatis的主配置文件
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		Resource mybatisConfigXml = resolver.getResource("classpath:mybatis-config.xml");
		sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
		// 扫描mapper文件
		Resource[] resoures = null;
		try {
			resoures = resolver.getResources("classpath:com/wx/entitys/*.xml");
		} catch (IOException e) {
			e.printStackTrace();
		}
		sqlSessionFactoryBean.setMapperLocations(resoures);
		return sqlSessionFactoryBean;
	}

	
	@Bean
	public SqlSessionTemplate sqlTemplate() {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}

我们也可以和传统的整合方式做一下对比

================context.xml============

<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="druidDataSource"></property>
		<property name="configLocation">
			<value>classpath:configs/mybatis-config.xml</value>
		</property>
		<property name="mapperLocations">
			<list>
				<value>classpath:com/wx/entitys/*.xml</value>
			</list>
		</property>
	</bean>
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg name="sqlSessionFactory" ref="sessionFactory"></constructor-arg>
	</bean>

好了,接下来来编写测试类

===============================TestConfig01.java=======================

package com.wx.test;

import java.util.List;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.wx.biz.UserBiz;
import com.wx.configs.SpringConfig;
import com.wx.entitys.UserEntity;

public class TestConfig01 {
	public static void main(String[] args) {
		//通过java配置来实例化spring容器
		AnnotationConfigApplicationContext ctx=
				new AnnotationConfigApplicationContext(SpringConfig.class);
		//在spring容器中获取bean对象
		//名称userBiz是注解根据类UserBiz自动生成的
		UserBiz userBiz=(UserBiz)ctx.getBean("userBiz");
		//或者采取下面的方式
		//UserBiz userBiz=(UserBiz)ctx.getBean(UserBiz.class);
		List<UserEntity> userList=userBiz.queryUserList();
		for(UserEntity user:userList){
			System.out.print(user.getUserId());
			System.out.print("\t"+user.getUserName());
			System.out.print("\t"+user.getPassWord());
			System.out.println("\t"+user.getEmail());
		}
		try {
			Thread.sleep(100000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//销毁容器
		ctx.destroy();
	}
}

 

 

 

 

 

 

 



 


 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

御前两把刀刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值