spring整合mybatis详细教程,保姆式案例讲解

本文详述了如何将Mybatis与Spring进行整合,通过引入相关jar包,创建实体类和Mapper接口,设置配置文件,实现Spring管理Mybatis。文中以User类为例,展示了注解和XML两种方式的SQL映射,并提供了业务层代码和测试类,帮助读者掌握整合过程。

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

在学习完mybatis框架和spring框架之后,要做的一件事情就是框架整合,将mybatis的部分配置交由spring管理,简化mybatis的配置。

在项目开始之前,需要将spring用到的jar包,mybatis的jar包以及整合两者需要的mybatis-spring-2.0.6.jar导入到项目中,同时也可以将lombok-1.18.16.jar导入项目,减少在实体类中写setter/getter及toString方法,节省开发时间。

然后创建实体类,以操作User类为例:

package cn.com.lzxh.pojo;

import lombok.Data;

/*
 * @Data注解可以自动生成setter/getter、toString()等方法
 * */
@Data
public class User {
	private Integer id;
	private String name;
	private String sex;
	private int age;
}

创建Mapper接口,在这里,我们创建两个方法,一个方法使用注解配置的方式实现SQL映射,一个方法使用XML配置的方法实现SQL映射,如下:

package cn.com.lzxh.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import cn.com.lzxh.pojo.User;

public interface UserMapper {

    //注解配置SQL映射
	@Select("select * from user where id=#{id}")
	User findOne(int id);
	
	//XML配置SQL映射,SQL语句在XML中
	List<User> findAll();
}

添加spring的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://mybatis.org/schema/mybatis-spring
        http://mybatis.org/schema/mybatis-spring.xsd">
        
        <!-- 自动扫描 -->
        <context:component-scan base-package="cn.com.lzxh"/>
        
        <!-- 加载外部资源 -->
        <context:property-placeholder location="classpath:jdbc.properties"/>
        
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		    <property name="driverClassName" value="${driver}"/>
		    <property name="url" value="${url}"/>
		    <property name="username" value="${jdbc.userName}"/>
		    <property name="password" value="${password}"/>
		</bean>
		
		<!-- 配置sqlSessionFactory -->
		<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		  <property name="dataSource" ref="dataSource" />
		  <!-- 添加mybatis的配置文件,如果mapper接口只使用注解实现SQL映射,则不需要这个配置 -->
		  <property name="configLocation" value="mybatis-config.xml"/>
		</bean>
		
		<!-- 
			映射器的配置有两种方法:
				1.注册映射器,相当于注册单个bean
				2.发现映射器,相当于自动扫描<context:component-scan>
		 -->
		<!-- 发现映射器 -->
		<mybatis:scan base-package="cn.com.lzxh.mapper"/>
		
		<!-- 注册映射器 -->
		<!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		  <property name="mapperInterface" value="cn.com.lzxh.mapper.UserMapper" />
		  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
		</bean> -->
        
</beans>

jdbc.properties属性文件:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
jdbc.userName=root
password=root

 UserMapper.xml映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.lzxh.mapper.UserMapper">
	<select id="findAll" resultType="User">
		select * from User
	</select>
</mapper>

注意,在上述映射文件中,resultType的配置使用了别名的方式,因此,在mybatis的配置文件中需要配置别名,而其他如sqlSessionFactory,mapper都已配置在spring中,mybatis-config.xml文件如下,如果mapper接口只用注解配置,则可以不创建该文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

	<typeAliases>
		<package name="cn.com.lzxh.pojo"/>
	</typeAliases>
	
</configuration>

业务层代码如下:

package cn.com.lzxh.service.impl;

import java.util.List;

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

import cn.com.lzxh.mapper.UserMapper;
import cn.com.lzxh.pojo.User;
import cn.com.lzxh.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

	//在spring配置文件中注册好mapper,在代码中即可使用自动注入获取mapper
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public User findOne(int id) {
		return userMapper.findOne(id);
	}

	@Override
	public List<User> findAll() {
		return userMapper.findAll();
	}

}

测试类代码:

package cn.com.lzxh.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.com.lzxh.pojo.User;
import cn.com.lzxh.service.UserService;
import cn.com.lzxh.service.impl.UserServiceImpl;

public class Test {

	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("spring-beans.xml");
		UserService us = ac.getBean("userService", UserServiceImpl.class);
		User u = us.findOne(2);
		System.out.println(u);
		System.out.println("------------------------------------------");
		List<User> list = us.findAll();
		for(User user : list) {
			System.out.println(user);
		}
	}

}

运行结果如下:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值