myBatis应用

http://lzh166.iteye.com/blog/1050911

最近项目中使用myBatis(iBatis),所以目前对所遇的一些问题及有些模糊的地方在这里标注一下。

首先mybaits是一个“半自动化”的ORM框架。

需要使用的jar包:mybatis-3.0.2.jar(mybatis核心包),mybatis-spring-1.0.0.jar(与spring结合jar包)这些jar可以去官网下载。

配置文件:

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>   
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"   
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  4. <configuration>  
  5.     <settings>  
  6.         <!-- 对在此配置文件下的所有cache进行全局性开/关设置 true|false true -->  
  7.         <setting name="cacheEnabled" value="true"/>  
  8.         <!-- 全局性设置懒加载。如果设为‘关',则所有相关联的都会被初始化加载。 -->  
  9.         <setting name="lazyLoadingEnabled" value="false"/>  
  10.         <!-- 当设置为‘开’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。 -->  
  11.         <setting name="aggressiveLazyLoading" value="true"/>  
  12.         <!-- 允许和不允许单条语句返回多个数据集(取决于驱动需求) -->  
  13.         <setting name="multipleResultSetsEnabled" value="true"/>  
  14.         <!-- 使用列标签代替列名称。不用的驱动器有不同的作法。 -->  
  15.         <setting name="useColumnLabel" value="true"/>  
  16.         <!-- 允许JDBC生成主键。需要驱动器支持.如果设为了true,这个设置将强制使用被生成的主键,  
  17.         有一些驱动器不兼容不过仍然可以执行。 -->  
  18.         <setting name="useGeneratedKeys" value="true"/>  
  19.         <!-- 指定MyBatis是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,NONE没有嵌套的结果。  
  20.         FULL将自动映射所有复杂的结果。  -->  
  21.         <setting name="autoMappingBehavior" value="PARTIAL"/>  
  22.         <!-- 配置和设定执行器,SIMPLE执行器执行其它语句。REUSE执行器可能重复使用preparedstatements语句,BATCH执行器可以重复执行语句和批量更新。 -->  
  23.         <setting name="defaultExecutorType" value="SIMPLE"/>  
  24.         <!-- 设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时. 正整数 -->  
  25.         <setting name="defaultStatementTimeout" value="25000"/>  
  26.     </settings>  
  27.       
  28.     <!-- 类型别名 -->  
  29.     <typeAliases>  
  30.         <typeAlias type="com.igit.storage.client.model.ClientRelation" alias="ClientRelation"/>  
  31.     </typeAliases>  
  32.       
  33.     <!-- 分页查询拦截器   
  34.     <plugins>  
  35.         <plugin interceptor="com.igit.storage.util.DiclectStatementHandlerInterceptor"></plugin>  
  36.         <plugin interceptor="com.igit.storage.util.DiclectResultSetHandlerInterceptor"></plugin>  
  37.     </plugins>  
  38.     -->  
  39.     <!-- 加载映射文件 -->  
  40.     <mappers>  
  41.         <mapper resource="com/igit/storage/client/model/ClientRelation.xml"/>  
  42.     </mappers>  
  43. </configuration>   

映射文件:

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC   
  3.  "-//mybatis.org//DTD Mapper 3.0//EN"   
  4.  "<href="http://mybatis.org/dtd/mybatis-3-mapper.dtd">http://mybatis.org/dtd/mybatis-3-mapper.dtd</a>">  
  5. <!-- 定义命名空间 -->   
  6. <mapper namespace="com.igit.storage.client.model.ClientRelation">  
  7.  <resultMap type="ClientRelation" id="relationResult"><!-- 对象应用关联查询 -->  
  8.   <association property="client" column="clientId" javaType="Client" select="com.igit.storage.client.model.Client.selectById">  
  9.   </association>  
  10.  </resultMap>  
  11.  <insert id="insert" parameterType="ClientRelation" useGeneratedKeys="true" keyProperty="id">  
  12.    insert into S_ClientRelation(relation,clientId)  
  13.     values(#{relation},#{client.clientId})  
  14.  </insert>  
  15.    
  16.  <delete id="delete" parameterType="long" flushCache="true">  
  17.    delete from S_ClientRelation where relation=#{value}  
  18.  </delete>  
  19.  <!-- flushCache="true" 清空缓存 -->  
  20.  <delete id="remove"  parameterType="long" flushCache="true">  
  21.    delete from S_ClientRelation where id=#{id}  
  22.  </delete>  
  23.  <!-- 批量删除多个,参数是数组  key为array  map-->  
  24.  <delete id="removeMore"  parameterType="map" flushCache="true">  
  25.    delete from S_ClientRelation   
  26.    where id in   
  27.    <foreach collection="array" index="index" item="ids" open="(" separator="," close=")">  
  28.    #{ids}  
  29.    </foreach>  
  30.  </delete>  
Xml代码  收藏代码
  1.  <select id="selectById" resultMap="relationResult" parameterType="long">  
  2.    select * from S_ClientRelation where id=#{value}  
  3.  </select>  
  4.    
  5.  <select id="selectByRelation" resultMap="relationResult" parameterType="long">  
  6.    select * from S_ClientRelation where relation=#{value}  
  7.  </select>  
  8.    
  9.  <select id="selectByPage" resultMap="relationResult">  
  10.   select * from S_ClientRelation   
  11.  </select>  
  12.    
  13.  <select id="selectByCount" resultType="long">  
  14.   select count(*) from S_ClientRelation   
  15.  </select>  
  16.    
  17.  <select id="selectMaxRelation" resultType="long">  
  18.   select max(relation) from s_clientRelation  
  19.  </select>  
  20. </mapper>  

修改application.xml文件

Xml代码  收藏代码
  1. <!-- 因为Hibernate的TransactionManager可以向下兼容JdbcTransactionManager,所以 mybatis事务处理仍和hibernate共用-->  
  2.  <bean id="transactionManager"  
  3.   class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  4.   <property name="sessionFactory">  
  5.    <ref local="sessionFactory" />  
  6.   </property>  
  7.  </bean>  
Xml代码  收藏代码
  1.  <!-- 用注解来实现事务管理 -->     
  2.  <tx:annotation-driven transaction-manager="transactionManager"/>   
  3.    
  4.  <tx:advice id="txAdvice" transaction-manager="transactionManager">  
  5.   <tx:attributes>  
  6.    <tx:method name="*" />  
  7.   </tx:attributes>  
  8.  </tx:advice>  
Xml代码  收藏代码
  1. <!-- mybatis  sqlSessionFactory 注入datasource和配置文件-->  
  2.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">    
  3.         <property name="configLocation" value="classpath:mybatisconfig.xml" />    
  4.         <property name="dataSource" ref="dataSource" />    
  5.     </bean>  
  6.     <!-- 定义mybatis操作模板类似hibernateTemplate -->  
  7.     <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">  
  8.         <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>  
  9.     </bean>  

代码实现

Java代码  收藏代码
  1. package com.igit.storage.client.service.imp;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import org.apache.ibatis.session.RowBounds;  
  8. import org.mybatis.spring.SqlSessionTemplate;  
  9. import org.springframework.util.Assert;  
  10. import org.springside.core.dao.Page;  
  11.   
  12. import com.igit.exception.BusinessException;  
  13. import com.igit.storage.client.model.Client;  
  14. import com.igit.storage.client.model.ClientRelation;  
  15. import com.igit.storage.client.service.ClientRelationService;  
  16.   
  17. public class ClientRelationServiceImp implements ClientRelationService {  
  18.       
  19.     private SqlSessionTemplate sqlSessionTemplate;  
  20.     /** 
  21.      * 新增关联客户 
  22.      */  
  23.     public void addRelationByClients(Long relation, List<Client> clients) {  
  24.         //判断该关联id是否存在  
  25.         if(!isValidRelation(relation)){  
  26.             throw new BusinessException("该关联关系不存在!");  
  27.         }  
  28.         //新增关联客户  
  29.         for(Client client : clients){  
  30.             ClientRelation cr = new ClientRelation();  
  31.             cr.setRelation(relation);  
  32.             cr.setClient(client);  
  33.             Assert.notNull(client, "客户不能为Null");  
  34.             sqlSessionTemplate.insert(ClientRelation.class.getName()+".insert", cr);  
  35.         }  
  36.     }  
  37.     /** 
  38.      * 取消关联客户 
  39.      */  
  40.     public void cancelRelation(Long relation) {  
  41.         sqlSessionTemplate.delete(ClientRelation.class.getName()+".delete", relation);  
  42.     }  
  43.   
  44.     /** 
  45.      * 创建关联客户 
  46.      */  
  47.     public void createRelation(List<Client> clients) {  
  48.         // 客户是否可以创建关联  
  49.         if(clients.size()<=1){  
  50.             throw new BusinessException("无法创建关联,关联客户不能低于2个!");  
  51.         }  
  52.         ClientRelation cr = new ClientRelation();  
  53.         cr.setRelation(getMaxRelation());  
  54.         //创建关联客户  
  55.         for(Client client : clients){  
  56.             cr.setClient(client);  
  57.             Assert.notNull(client, "客户不能为Null");  
  58.             sqlSessionTemplate.insert(ClientRelation.class.getName()+".insert", cr);  
  59.         }  
  60.   
  61.     }  
  62.     /** 
  63.      * 获取最大关联ID 
  64.      * @return 
  65.      */  
  66.     private Long getMaxRelation(){  
  67.         Long relation = 1L;  
  68.         Long maxRelation = (Long) sqlSessionTemplate.selectOne(ClientRelation.class.getName()+".selectMaxRelation");  
  69.         if(maxRelation==null){  
  70.             return relation;  
  71.         }  
  72.         return maxRelation+1;  
  73.     }  
  74.   
  75.     /** 
  76.      * 分页获取关联客户 
  77.      */  
  78.     public Page getClientRelationByPage(int startIndex, int pageSize) {  
  79.         List<ClientRelation> list = sqlSessionTemplate.selectList(ClientRelation.class.getName()+".selectByPage", new RowBounds(startIndex,pageSize));  
  80.         Long totalCount = (Long) sqlSessionTemplate.selectOne(ClientRelation.class.getName()+".selectByCount");  
  81.         return new Page(list,totalCount,pageSize,startIndex);  
  82.     }  
  83.   
  84.     /** 
  85.      *  获取没有关联的客户列表 
  86.      */  
  87.     public Page getNoRelationClients(int startIndex,int pageSize) {  
  88.         List<Client> list = sqlSessionTemplate.selectList(Client.class.getName()+".selectSingleClient", new RowBounds(startIndex,pageSize));  
  89.         Long totalCount = (Long) sqlSessionTemplate.selectOne(Client.class.getName()+".selectSingleCount");  
  90.         return new Page(list,totalCount,pageSize,startIndex);  
  91.     }  
  92.   
  93.     /** 
  94.      * 删除关联客户 
  95.      */  
  96.     public void removeRelationByClients(Long relation, List<Client> clients) {  
  97.         //1.该客户是否可以从关联中移除  
  98.         List<ClientRelation> list = getRelationClients(relation);  
  99.         if((list.size()-clients.size())<=1){  
  100.             throw new BusinessException("不允许删除,关联客户至少存在2个!");  
  101.         }  
  102.         //2.移除客户  
  103.         for(Client c : clients){  
  104.             Map<String,Long> params = new HashMap<String,Long>();  
  105.             params.put("relation", relation);  
  106.             params.put("clientId", c.getClientId());  
  107.             sqlSessionTemplate.delete(ClientRelation.class.getName()+".remove", params);  
  108.         }  
  109.     }  
  110.   
  111.       
  112.     private boolean isValidRelation(Long relation) {  
  113.         List<ClientRelation> list = getRelationClients(relation);  
  114.         if(list.size()<=1){  
  115.             return false;  
  116.         }  
  117.         return true;  
  118.     }  
  119.   
  120.     private List<ClientRelation> getRelationClients(Long relation) {  
  121.         List<ClientRelation> list = sqlSessionTemplate.selectList(ClientRelation.class.getName()+".selectByRelation", relation);  
  122.         return list;  
  123.     }  
  124.   
  125.     public SqlSessionTemplate getSqlSessionTemplate() {  
  126.         return sqlSessionTemplate;  
  127.     }  
  128.   
  129.     public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {  
  130.         this.sqlSessionTemplate = sqlSessionTemplate;  
  131.     }  
  132. }  

  

单元测试请看上一篇文章

原文地址:https://www.cnblogs.com/zdl3ng/p/4587491.html