SpringMVC3+MyBatis3整合的笔记

在公司基础框架的基础之上增加多数据源的支持,公司框架底层是用hibernate的,现增加mybatis作为底层的一个新的数据源。

1、增加jar包

基础框架采用spring版本是3.1,所以需要根据此版本加入对应的mybatis版本,分别加入mybatis-spring-1.0.2.jar和mybatis-3.0.6.jar即可。

2、增加spring的mybatis配置文件

<!-- 数据库连接池,使用阿里巴巴开源数据库连接 -->
	<bean id="dataSource3" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<property name="driverClassName">
			<value>oracle.jdbc.driver.OracleDriver</value>
		</property>
		<property name="url">
			<value>jdbc:oracle:thin:@218.15.22.15:1521:orcl</value>
		</property>
		<property name="username">
			<value>callplat123</value>
		</property>
		<property name="password">
			<value>YRwDHYuisdwtEUgxp3rwf8QhYi40hWE+zIWlr6HcmIZfqFRjk662lESHAt0u3vqWFd4XW65yLkJe6M/tQAT88w==</value>
		</property>
		<!-- 数据库解密 -->
		<property name="connectionProperties" value="config.decrypt=true" />
		<property name="filters" value="config" />
		<property name="maxActive" value="50" />
		<property name="initialSize" value="3" />
		<property name="maxWait" value="60000" />
		<property name="minIdle" value="3" />
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<property name="validationQuery" value="SELECT 'x' from DUAL" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="50" />
	</bean>


	<bean id="sessionFactory3" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource3" />  
        <!-- 配置mybatis 数据源、别名等信息
        <property name="configLocation" value="classpath:config/mybatis-config-slave.xml" />
         -->
        <property name="mapperLocations" value="classpath*:com/mybatis/*/mapping/*.xml" />  
    </bean>
    
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.mybatis" />  
        <property name="sqlSessionFactory" ref="sessionFactory3"/>
    </bean>

	<!-- 事务配置 -->
	<bean id="transactionManager3" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource3" />  
    </bean>
	
	<!-- 事务规则 -->
	<tx:advice id="txAdvice3" transaction-manager="transactionManager3">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="modify*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>

	<!-- 仅对service包下面的方法开启事务控制 -->
	<aop:config>
		<aop:pointcut id="interceptorPointCuts3" expression="execution(* com.mybatis..service.*.*(..))" />
		<aop:advisor advice-ref="txAdvice3" pointcut-ref="interceptorPointCuts3" />
	</aop:config>

 3、根据mysql数据库对应表、表到代码的配置文件及依赖的生成工具jar进行生成代码

<?xml version="1.0" encoding="UTF-8"?>    
<!DOCTYPE generatorConfiguration    
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"    
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">    
<generatorConfiguration>    
<!-- 数据库驱动-->    
    <classPathEntry  location="mysql-connector-java-3.1.14-bin.jar"/>    
    <context id="DB2Tables"  targetRuntime="MyBatis3">    
        <commentGenerator>    
            <property name="suppressDate" value="true"/>    
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->    
            <property name="suppressAllComments" value="true"/>    
        </commentGenerator>    
        <!--数据库链接URL,用户名、密码 -->    
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&amp;characterEncoding=utf8" userId="root" password="root">    
        </jdbcConnection>    
        <javaTypeResolver>    
            <property name="forceBigDecimals" value="false"/>    
        </javaTypeResolver>    
        <!-- 生成模型的包名和位置-->    
        <javaModelGenerator targetPackage="com.cn.hnust.entity" targetProject="src">    
            <property name="enableSubPackages" value="true"/>    
            <property name="trimStrings" value="true"/>    
        </javaModelGenerator>    
        <!-- 生成映射文件的包名和位置-->    
        <sqlMapGenerator targetPackage="com.cn.hnust.mapping" targetProject="src">    
            <property name="enableSubPackages" value="true"/>    
        </sqlMapGenerator>    
        <!-- 生成DAO的包名和位置-->    
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.cn.hnust.dao" targetProject="src">    
            <property name="enableSubPackages" value="true"/>    
        </javaClientGenerator>    
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->    
        <table tableName="user_t" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>  
    </context>    
</generatorConfiguration>

 需要依赖到的工具包为mybatis-generator-core-1.3.2.jar和驱动包mysql-connector-java-3.1.14-bin.jar,将jar和配置文件放在一个目录下并在此目录创建src文件夹,打开命令窗口定位到此目录,敲入命令:java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite 进行生成对应的代码

4、生成的pojo类和xml文件

package com.cn.hnust.entity;

public class User {
    private Integer id;

    private String userName;

    private String password;

    private Integer age;

    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 == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

                                                  pojo 类

<?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.cn.hnust.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.cn.hnust.entity.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, user_name, password, age
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user_t
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from user_t
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.cn.hnust.entity.User" >
    insert into user_t (id, user_name, password, 
      age)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{age,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.cn.hnust.entity.User" >
    insert into user_t
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="age != null" >
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.cn.hnust.entity.User" >
    update user_t
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.cn.hnust.entity.User" >
    update user_t
    set user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

                                                    mybatis-xml配置文件

5、编写单元测试类进行测试表的增删改查

package com.cn.hnust.test;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.cn.hnust.dao.UserMapper;
import com.cn.hnust.entity.User;

@RunWith(SpringJUnit4ClassRunner.class)     //表示继承了SpringJUnit4ClassRunner类  
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class TestMyBatis {

	
	private static Logger logger = Logger.getLogger(TestMyBatis.class);  
    @Resource  
    private UserMapper userMapper;
  
  
    @Test  
    public void test() { 
    	logger.info("测试方法");
    	try {
    		User user = userMapper.selectByPrimaryKey(new Integer(1)); 
    		logger.info("user:"+user);
    		if(user != null){
    			System.out.println(user.getUserName()+":"+user.getPassword());
    		}
    		user.setAge(100);
    		user.setUserName("我是中国人");
    		userMapper.updateByPrimaryKey(user);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
    }
}

 至此,一个简单SpringMVC3+Mybatis3整合到此结束!

扫描二维码关注公众号,回复: 497192 查看本文章

猜你喜欢

转载自zcz123.iteye.com/blog/2364731