MyBatis学习笔记(三)

来源:互联网 发布:p4vasp windows安装 编辑:程序博客网 时间:2024/05/03 15:28

MyBatis学习笔记(三)

常用批量操作,Spring与myBatis整合,简化配置

个人笔记,如有错误,恳请批评指正。

常用批量操作

批量新增部门

映射文件定义SQL
<!-- 批量增加 -->    <!-- insert into dept(dept_name,dept_address) values(name1,address1)(name2,address2)...(); -->    <sql id="key">        <trim suffixOverrides=",">            dept_name,            dept_address,        </trim>    </sql>    <insert id="insertDeptList">        insert into dept(    <include refid="key"></include>        ) values            <foreach collection="list" item="dept" separator=",">                (#{dept.deptName},#{dept.deptAddress})            </foreach>    </insert>
编写批量添加部门方法

数据操作类定义批量添加部门的方法

public int insertDeptList(List list){        int i = 0;        try {            session = MybatisSessionFactory.getSession();            i = session.insert("cn.ustb.entity.DeptMapper.insertDeptList", list);            session.commit();        } catch (Exception e) {            e.printStackTrace();            session.rollback();        }        finally{            MybatisSessionFactory.closeSession();        }        return i;    }

批量删除部门

映射文件定义SQL
<!-- 批量删除 -->    <delete id="deleteDeptList" parameterType="string">        delete from dept where dept_id in (            <foreach collection="array" item="id" separator=",">                #{id}            </foreach>        );      </delete>
编写批量删除部门的方法
public int deleteDeptList(String[] ids){        int i = 0;        try {            session = MybatisSessionFactory.getSession();            i = session.delete("cn.ustb.entity.DeptMapper.deleteDeptList", ids);            session.commit();        } catch (Exception e) {            e.printStackTrace();            session.rollback();        }        finally{            MybatisSessionFactory.closeSession();        }        return i;    }

批量修改员工信息

修改mybatis-config.xml文件
支持上有点麻烦,需要修改mybatis-config.xml文件相关数据库连接的信息(主要url),以支持批量更新        <environments default="development">        <environment id="development">            <transactionManager type="JDBC" />            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver"></property>                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;allowMultiQueries=true" />                <property name="username" value="root"></property>                <property name="password" value="root"></property>            </dataSource>        </environment>        <environment id="test">            <transactionManager type=""/>            <dataSource type=""></dataSource>        </environment>    </environments>
配置批量更新的sql
<!-- 批量更新 -->    <update id="updateDeptList">        <foreach collection="list" item="dept" separator=";">            update dept             <set>                <if test="dept.deptName!=null">dept_name = #{dept.deptName},</if><!-- ','necessary -->                <if test="dept.deptAddress!=null">dept_address = #{dept.deptAddress},</if>            </set>            where dept_id = #{dept.deptId}        </foreach>    </update>
编写批量更新部门的方法
public int updateDeptList(List list){        int i = 0;        try {            session = MybatisSessionFactory.getSession();            i = session.update("cn.ustb.entity.DeptMapper.updateDeptList", list);            session.commit();        } catch (Exception e) {            e.printStackTrace();            session.rollback();        }        finally{            MybatisSessionFactory.closeSession();        }        return i;    }

Spring+myBatis整合

准备工作

  • 新建项目并导入jar包
  • 配置mybatis-config.xml
  • 创建库及表
  • 创建实体
  • 编写映射文件,修改mybatis-config.xml内容
  • 进行简单测试(除了导入spring相关jar包外,以上内容可能直接使用上一章节内容)

配置applicationContext.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:tx="http://www.springframework.org/schema/tx"    xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:p="http://www.springframework.org/schema/p"    xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd    http://www.springframework.org/schema/tx     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">    <!-- 配置数据源,记得去掉myBatis-config.xml的数据源相关配置 -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">                    <property name="driverClass" value="com.mysql.jdbc.Driver" />        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8" />        <property name="user" value="root" />        <property name="password" value="root" />           </bean>    <!-- 配置session工厂 -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <property name="configLocation" value="classpath:myBatis-config.xml" />        <property name="mapperLocations" value="classpath:cn/ustb/entity/*.xml"/>    </bean>    <!-- 配置事务管理器,管理数据源事务处理-->    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource"/>    </bean>    <!-- deptDao的实现类对象 -->    <bean id="deptDao" class="cn.ustb.dao.impl.DeptDaoImpl">        <property name="sqlSessionTemplate" ref="sqlSessionTemplate"></property>    </bean>    <!-- 配置SessionTemplate,已封装了繁琐的数据操作-->    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>         </bean> </beans>

修改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>    <typeAliases>        <typeAlias type="cn.ustb.entity.Dept" alias="Dept" />    </typeAliases>    <mappers>        <mapper resource="cn/ustb/entity/DeptMapper.xml" />    </mappers></configuration>

编写dao层接口及实现

DeptDao.java

public interface DeptDao {    //根据部门ID查询部门信息    public Dept selectOne(int deptId);}

修改接口实现类:DeptDaoImpl.java

public class DeptDaoImpl {    private SqlSessionTemplate sqlSessionTemplate;    public SqlSessionTemplate getSqlSessionTemplate() {        return sqlSessionTemplate;    }    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {        this.sqlSessionTemplate = sqlSessionTemplate;    }    public Dept selectOne(int deptId){        Dept dept = null;        dept = sqlSessionTemplate.selectOne("cn.ustb.entity.DeptMapper.selectOne", deptId);        return dept;    }}

编写业务层代码
业务层接口略,这里只写业务层实现类:DeptServiceImpl.java

public class DeptServiceImpl {    private DeptDao deptDao;    public DeptDao getDeptDao() {        return deptDao;    }    @Resource    public void setDeptDao(DeptDao deptDao) {        this.deptDao = deptDao;    }    public Dept selectOne(int id){        return deptDao.selectOne(id);    }    public int insertDept(Dept dept){        return deptDao.insertDept(dept);    }}

配置bean信息到sping配置文件

<!-- DAO层部门信息表的数据操作对象 --><bean id="deptDao" class="cn.ustb.dao.impl.DeptDaoImpl" >    <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/></bean><!-- 业务层部门信息业务处理对象 --><bean id="deptService" class="cn.ustb.service.impl.DeptServiceImpl">    <property name="deptDao" ref="deptDao"/></bean>

简化配置

扫描式加载SQL映射文件

修改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>    <typeAliases>        <typeAlias type="cn.ustb.entity.Dept" alias="Dept" />    </typeAliases>    <!-- 采用扫描式加载映射文件,以下将不用配置,可以减少映射文件过多时维护的麻烦 -->    <!-- <mappers>        <mapper resource="cn/ustb/entity/DeptMapper.xml" />    </mappers>    --></configuration>

修改applicationContext.xml,为SqlSessionFactoryBean设置mapperLocations属性

<!-- 配置session工厂 -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <property name="configLocation" value="classpath:myBatis-config.xml" />        <!-- 配置扫描式加载SQL映射文件 -->        <property name="mapperLocations" value="classpath:cn/ustb/entity/*.xml"/>    </bean>

MapperScannerConfigurer简化配置

1. 在spring配置文件中添加MapperScannerConfigurer 配置并去掉所有的Dao接口实现类配置
<!-- 配置 转换器,对于在basePackage设置的包(包括子包)下的接口类的全类名和在Mapper.xml文件中定义过的命名空间一致,    spring将会生成对应的代理对象(在调用 的地方通过@Autowired或者@Resource方式将可以注入接口实例)-->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>        <property name="basePackage" value="cn.ustb.dao"/>    </bean>    <!-- DAO层部门信息表的数据操作对象,上面如果配置MapperScannerConfigurer转换器,DAO接口将不再使用实现类 -->    <!--     <bean id="deptDao" class="cn.ustb.dao.impl.DeptDaoImpl" >        <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>    </bean>     -->    <!-- 业务层部门信息业务处理对象 -->    <bean id="deptService" class="cn.ustb.service.impl.DeptServiceImpl">    <!-- 上面如果配置MapperScannerConfigurer转换器,DAO接口将不再使用实现类注入 -->        <!-- <property name="deptDao" ref="deptDao"/>  -->    </bean>
2. 检查或修改DeptMapper.xml文件

注意:命名空间+id和接口+方法名 一致

<?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"><!-- 这时的命名空间就需要和dao接口类全类名一致了 --><mapper namespace="cn.ustb.dao.DeptDao">    <resultMap id="deptResultMap" type="Dept">        <id property="deptId" column="dept_id" />        <result property="deptName" column="dept_name" />        <result property="deptAddress" column="dept_address" />    </resultMap>    <!-- 这时的id就需要和dao接口的方法一致了 -->    <select id="selectOne" parameterType="int" resultMap="deptResultMap">        select * from dept where dept_id=#{id}    </select></mapper>
3. 业务类中,使用@Autowired为DAO接口注入对象public class DeptServiceImpl {
@Autowired    private DeptDao deptDao;//省略其它代码
4. 删除Dao实现类(存在也没有意义)
0 0
原创粉丝点击