spring集成mybatis简单示例

本文介绍了Spring与MyBatis的整合,整合后数据库配置交予Spring,SqlSessionFactory也由其管理。详细说明了构建Maven工程、准备实体类和接口等准备工作,还通过单元测试检验整合情况,重点提及事务管理测试及Spring配置文件中mapperScannerConfigurer的属性设置。

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

mybatis作为一个持久层框架,很少单独使用,一般都是和spring集成,和spring集成,mybatis-config.xml配置文件就不需要了,数据库相关配置全部交给spring,SqlSessionFactory就交给spring管理,同时需要一个数据源dataSource,最后再配置一个事务管理器就差不多了。这里仅仅介绍spring与mybatis的整合。

构建maven工程,添加相关依赖:

<dependencies>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.4.6</version>
</dependency>
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis-spring</artifactId>
	<version>1.3.2</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context-support</artifactId>
	<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
	<version>4.3.13.RELEASE</version>
</dependency>

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-test</artifactId>
	<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
	<groupId>com.zaxxer</groupId>
	<artifactId>HikariCP</artifactId>
	<version>2.7.9</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.46</version>
</dependency>
<dependency>
	<groupId>org.aspectj</groupId>
	<artifactId>aspectjweaver</artifactId>
	<version>1.8.13</version>
</dependency>
</dependencies>

准备实体类和dao,service层接口:

User.java

package com.xxx.mybatis.domain;

public class User {
	private Integer id;
	private String username;
	private String password;
	private Double balance;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public void setBalance(Double balance) {
		this.balance = balance;
	}
	
	public Double getBalance() {
		return balance;
	}
	
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}
	
}

UserDao.java

package com.xxx.mybatis.dao;
import java.util.List;
import java.util.Map;
import com.xxx.mybatis.domain.User;
public interface UserDao {
	public User findById(Integer id);
	public int insert(Map<String, Object> params);
	public int update(Map<String, Object> params);
	public int delete(Integer id);
	public List<User> findAll();
	public void updateBalance(Map<String, Object> params);
}

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="com.xxx.mybatis.dao.UserDao">
    <select id="findById" resultType="com.xxx.mybatis.domain.User">
       select * from xx_user where id = #{id}
    </select>
    <insert id="insert">
    	insert into xx_user values(#{id},#{username},#{password})
    </insert>
    <update id="update">
    	update xx_user set 
    	username=#{username},
    	password = #{password}
    	where id = #{id}
    </update>
    <update id="updateBalance">
        update xx_user set
        balance = #{balance}
        where id = #{id}
    </update>
    <delete id="delete">
    	delete from xx_user where id = #{id}
    </delete>
    <select id="findAll" resultType="com.xxx.mybatis.domain.User">
    	select * from xx_user
    </select>
</mapper>

UserService.java

package com.xxx.mybatis.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xxx.mybatis.dao.UserDao;
import com.xxx.mybatis.domain.User;
@Service
public class UserService {
	@Autowired
	private UserDao userDao;
	public User findById(Integer id) {
		return userDao.findById(id);
	}
	public int insert(Map<String,Object> params) {
		return userDao.insert(params);
	}
	
	public int update(Map<String, Object> params) {
		return userDao.update(params);
	}
	
	public int delete(Integer id) {
		return userDao.delete(id);
	}
	
	public List<User> findAll(){
		return userDao.findAll();
	}
	
	
	public void transfer(Integer from,Integer to,double money){
		User user = userDao.findById(from);
		User user2 = userDao.findById(to);
		user.setBalance(user.getBalance() - money);
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("id", from);		
		params.put("balance", user.getBalance());
		userDao.updateBalance(params);
		int i = 1/0;
		System.out.println(i);
		user2.setBalance(user2.getBalance()+money);
		params.clear();
		params.put("id", to);
		params.put("balance", user2.getBalance());
		userDao.updateBalance(params);
	}
}

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&useSSL=false&characterEncoding=UTF-8
jdbc.username=hadoop
jdbc.password=hadoop

spring.xml

<?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:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    
    <context:property-placeholder location="classpath*:jdbc.properties"/>
    
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
       <property name="driverClassName" value="${jdbc.driver}" />
       <property name="jdbcUrl" value="${jdbc.url}" />
       <property name="username" value="${jdbc.username}" />
       <property name="password" value="${jdbc.password}" />
    </bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations"  value="classpath:com/xxx/mybatis/dao/*Mapper.xml"/>
    </bean>
    
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    	<property name="basePackage" value="com.xxx.mybatis.dao"/>
    </bean>
    
    <context:component-scan base-package="com.xxx.mybatis" />
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <property name="dataSource" ref="dataSource" />
    </bean>

    <tx:advice id="tx-advice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="transfer*" propagation="REQUIRED"/>  
        </tx:attributes>
    </tx:advice>
    
    <aop:config>
        <aop:pointcut expression="execution(* com.xxx.mybatis.service.*.*(..))" id="point-cut"/>
        <aop:advisor pointcut-ref="point-cut" advice-ref="tx-advice"/>
    </aop:config>
</beans>

至此,准备工作就做完了,我们准备一个单元测试类,测试我们集成的情况。

package com.xxx.mybatis;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.xxx.mybatis.domain.User;
import com.xxx.mybatis.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:spring.xml"})
public class JunitTest {
	@Autowired
	private UserService userService;
	
	@Test
	public void select() {
		User user = userService.findById(1);
		System.out.println(user);
	}
	
	@Test
	public void transfer(){
		userService.transfer(1, 2, 200);
	}
}

这里的单元测试很简单,就是测试一个查询方法,测试一个转账方法 。

这里如果查询方法没有问题,其他的service方法基本就可以跟着节奏来做,出不了大问题。spring与mybatis整合有个问题,就是事务管理,事务管理作用在service层,操作如果成功都成功,如果失败,全部回滚,这里准备了一个转账的测试用例,就是来测试事务的,这里的service方法里面,转账之后,模拟一个异常,这个异常会导致事务回滚,如果事务生效,那么转账操作是不会成功的,如果事务没有生效,那么转账过程,一个转出成功,第二个转入失败,这就会导致生产事故,所以这个测试示例可以检验我们的事务管理是否生效。

在spring配置文件中,需要注意一个地方,就是mapperScannerConfigurer这里,他需要一个属性为sqlSessionFactoryBeanName的属性,这个属性不能用ref来指定,必须使用value来指定,如下:

如果使用ref来指定,会报错: 

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mapperScannerConfigurer' defined in class path resource [spring.xml]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactoryBeanName'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [spring.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.RuntimeException: Failed to load driver class ${jdbc.driver} in either of HikariConfig class loader or Thread context classloader

映射文件与dao层接口放在一起,一个dao的接口方法名,对应一个mapper的子元素的ID。

到这里spring与mybatis简单整合基本结束,希望对初学的同学有帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

luffy5459

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

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

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

打赏作者

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

抵扣说明:

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

余额充值