(四)从零搭建maven+spring+mybatis项目之mybatis与事务配置

Java技术交流欢迎加群:587691476

感言:时间贼快,最近一直懒着,一下子就是一个月过去,本地Mybatis搭配已经完成,搭配之前博客分享一下。

1、spring+数据源+mybatis+事务配置

<?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.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 自动注入配置 -->      
    <context:component-scan base-package="com.min"/>
    <!-- jdbc配置文件引入 -->
	<context:property-placeholder location="classpath:jdbc.properties"
		ignore-unresolvable="true" />
    <!-- 数据源配置 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>
	<!-- mybatis配置 -->
	<bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	    <property name="dataSource" ref="dataSource"/>
	    <property name="configLocation" value="classpath:mybatis-config.xml"/>
	    <property name="mapperLocations" value="classpath:mybatis/*.xml"/>
	</bean>
	<bean id="mySqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="mySqlSessionFactory" />
	</bean>
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	    <property name="basePackage" value="com.min.dao"></property>
	    <property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory"></property>
	    <property name="sqlSessionTemplateBeanName" value="mySqlSession"></property>
	</bean>
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	   <property name="dataSource" ref="dataSource"/>
    </bean>
	<!--配置事务的传播性-->
	<tx:advice id="myAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="del*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="*" read-only="true" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice>

	<!--配置哪些类哪些方法使用事务-->
	<aop:config proxy-target-class="true">
		<aop:pointcut id="myServiceMethod"
			expression="execution(* com.min.service.*.*(..))" />
		<aop:advisor advice-ref="myAdvice" pointcut-ref="myServiceMethod" />
	</aop:config>  
</beans>

jdbc.properties配置

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/minyi?useUnicode\=true&characterEncoding\=utf-8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=123456
initialSize=0
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000

mybatis-config.xml配置

<?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>

	<!-- 配置mybatis的缓存,延迟加载等等一系列属性 -->
	<settings>
		<!-- 全局映射器启用缓存 -->
		<setting name="cacheEnabled" value="true" />
		<!-- 查询时,关闭关联对象即时加载以提高性能 -->
		<setting name="lazyLoadingEnabled" value="true" />
		<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
		<setting name="aggressiveLazyLoading" value="false" />
		<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
		<setting name="multipleResultSetsEnabled" value="true" />
		<!-- 允许使用列标签代替列名 -->
		<setting name="useColumnLabel" value="true" />
		<!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
		<!-- <setting name="useGeneratedKeys" value="true" /> -->
		<!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
		<setting name="autoMappingBehavior" value="FULL" />
		<!-- 对于批量更新操作缓存SQL以提高性能 -->
		<setting name="defaultExecutorType" value="REUSE" />
		<!-- 数据库超过25000秒仍未响应则超时 -->
		<setting name="defaultStatementTimeout" value="25000" />
	</settings>

</configuration> 

注意事项:事务部分使用了声明式配置,使用到了aop切入到service层具体方法中,所以需要后续引入aop相关包

    <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aspects</artifactId>
         <version>5.0.1.RELEASE</version>
    </dependency>
    <dependency>
         <groupId>org.aspectj</groupId>
         <artifactId>aspectjweaver</artifactId>
         <version>1.8.9</version>
    </dependency>
    <dependency>
         <groupId>org.aspectj</groupId>
         <artifactId>aspectjrt</artifactId>
         <version>1.8.9</version>
    </dependency>
    <dependency>
         <groupId>aopalliance</groupId>
         <artifactId>aopalliance</artifactId>
         <version>1.0</version>
    </dependency>


以上配置完成spring+mybatis+mysql+事务配置,下面开始使用测试用例进行测试配置

创建表

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(200) DEFAULT NULL,
  `school` varchar(200) DEFAULT NULL,
  `password` varchar(200) DEFAULT NULL,
  `sex` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

插入数据

insert into t_user(id,username,school,password,sex)values(1,'minyi','gzu','132456',1);

实体类

package com.min.entity;

public class UserEntity
{
    private int id;

    private String userName;

    private String password;

    private String school;

    private int sex;

    public int getId()
    {
        return id;
    }

    public void setId(int 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 String getSchool()
    {
        return school;
    }

    public void setSchool(String school)
    {
        this.school = school;
    }

    public int getSex()
    {
        return sex;
    }

    public void setSex(int sex)
    {
        this.sex = sex;
    }
 
}
dao层
package com.min.dao;

import java.util.List;

import com.min.entity.UserEntity;

public interface MinyiMapper
{
    List<UserEntity> selectAll();
}
MinyiMapper对应Mybatis配置文件

<?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.min.dao.MinyiMapper" >
   <resultMap id="BaseResultMap" type="com.min.entity.UserEntity" >
    <id column="id" property="id" jdbcType="DECIMAL" />
    <result column="username" property="userName" jdbcType="VARCHAR" />
    <result column="school" property="school" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="sex" property="sex" jdbcType="DECIMAL" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, username, school, password, sex
  </sql>
 
  <select id="selectAll" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from T_USER
  </select>
</mapper>
service接口
package com.min.service;

import com.min.entity.UserEntity;

public interface MinyiService
{
    UserEntity getAll();
}

package com.min.service.impl;

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.min.dao.MinyiMapper;
import com.min.entity.UserEntity;
import com.min.service.MinyiService;

@Service("minyiService")
public class MinyiServiceImpl implements MinyiService
{
    @Autowired
    @Qualifier("minyiMapper")
    private MinyiMapper minyiMapper;
    
    public UserEntity getAll()
    {
        List<UserEntity> userEntity=minyiMapper.selectAll();
        UserEntity userEntity2=userEntity.get(0);
        return userEntity2;
    }
    
}

测试用例
package test;

import com.min.entity.UserEntity;
import com.min.service.MinyiService;

public class SpringTest
{
    public static void main(String[] args)
    {
        MinyiService minyiService=BeanUtil.getBean("minyiService");
        UserEntity userEntity=minyiService.getAll();
        System.out.println("Spring+mybati+mysql配置运行成功!"+"姓名:"+userEntity.getUserName()+":学校"+userEntity.getSchool());
    }
}

BeanUtil前面有提到过,还是再发一遍
package test;

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

public class BeanUtil
{
    public static <T> T getBean(String beanName)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "spring.xml");
        Object object = context.getBean(beanName);
        return (T) object;
    }
}

运行结果

注意点:
1、注意引入aop相关包
2、配置${jdbc.driver}会报错,与sqlSessionFactoryBeanName的配置有点冲突,直接将driver配置到.xml文件中省事点,其他的在.properties中配置

工程源码在系列第五篇

最后 by 2017/12/6  0:25  迟来一个月的更新,下次配置dubbo。

 
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值