mybatis3学习笔记之Mapper编程

来源:互联网 发布:php 爬虫代码 编辑:程序博客网 时间:2024/06/06 12:51

参考源:

http://java.itcast.cn/news/20150512/13543033211.shtml 这是传智播客的燕青老师讲的 讲的很好 强烈推荐


[java] view plaincopy
  1. /** 
  2.  * Mapper接口 
  3.  * Mapper编程相比于自己编写Dao实现 
  4.  * 1、提取了Dao实现大量的模板代码 
  5.  * 2、避免了statement的硬编码 
  6.  * 3、避免了参数的传递为Object,在编译时即能检测出类型不正确 
  7.  * 4、传出参数的自动转换 
  8.  *  
  9.  * Mapper的Mapper接口文件与Mapper的配置文件遵循规则 
  10.  * 1、Mapper的配置文件的namespace值与Mapper接口文件的包一致 
  11.  * 2、Mapper配置文件的statement的编号与Mapper接口文件的方法名一致 
  12.  * 3、Mapper配置文件的statement的parameterType的类型与Mapper接口文件的方法的入参类型一致 
  13.  * 4、Mapper配置文件的statement的resultType的类型与Mapper接口文件的方法的返回值类型一致 
  14.  * @author u1 
  15.  * 
  16.  */  

相应的地方都加了必要的注释 以单元测试检验功能

单例获取SqlSessionFactory 工具类

[java] view plaincopy
  1. package com.undergrowth.mybatis.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5.   
  6. import org.apache.ibatis.io.Resources;  
  7. import org.apache.ibatis.session.SqlSessionFactory;  
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  9.   
  10. public class SqlSessionUtil {  
  11.   
  12.     private static SqlSessionFactory sqlSessionFactory;  
  13.   
  14.     /** 
  15.      * 单利获取SqlSessionFactory 
  16.      *  
  17.      * @param fileName 
  18.      *            mybatis配置的文件名 
  19.      * @return SqlSessionFactory 
  20.      * @throws IOException 
  21.      */  
  22.     public static SqlSessionFactory getSqlSessionFactory(String fileName)  
  23.             throws IOException {  
  24.         if (sqlSessionFactory == null) {  
  25.             synchronized (SqlSessionUtil.class) {  
  26.                 if (sqlSessionFactory == null) {  
  27.                     InputStream inputStream = Resources  
  28.                             .getResourceAsStream(fileName);  
  29.                     sqlSessionFactory = new SqlSessionFactoryBuilder()  
  30.                             .build(inputStream);  
  31.                 }  
  32.             }  
  33.         }  
  34.   
  35.         return sqlSessionFactory;  
  36.     }  
  37.   
  38. }  



Mapper接口

[java] view plaincopy
  1. package com.undergrowth.mybatis.mapper;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import com.undergrowth.mybatis.po.City;  
  7. import com.undergrowth.mybatis.po.CityQueryVo;  
  8.   
  9. /** 
  10.  * Mapper接口 
  11.  * Mapper编程相比于自己编写Dao实现 
  12.  * 1、提取了Dao实现大量的模板代码 
  13.  * 2、避免了statement的硬编码 
  14.  * 3、避免了参数的传递为Object,在编译时即能检测出类型不正确 
  15.  * 4、传出参数的自动转换 
  16.  *  
  17.  * Mapper的Mapper接口文件与Mapper的配置文件遵循规则 
  18.  * 1、Mapper的配置文件的namespace值与Mapper接口文件的包一致 
  19.  * 2、Mapper配置文件的statement的编号与Mapper接口文件的方法名一致 
  20.  * 3、Mapper配置文件的statement的parameterType的类型与Mapper接口文件的方法的入参类型一致 
  21.  * 4、Mapper配置文件的statement的resultType的类型与Mapper接口文件的方法的返回值类型一致 
  22.  * @author u1 
  23.  * 
  24.  */  
  25. public interface CityMapper {  
  26.   
  27.     public City fetchByCityById(int id);  
  28.   
  29.     public List<City> findCityByName(String name);  
  30.   
  31.     public void removeCityById(int id);  
  32.   
  33.     public void insertCity(City city);  
  34.   
  35.     public void insertCityAfter(City city);  
  36.   
  37.     public void updateCity(City city);  
  38.   
  39.     public int findCityCount(CityQueryVo vo);  
  40.   
  41.     public int findCityCountByIds(CityQueryVo vo);  
  42.       
  43.     public City findCityByHashmap(Map<String, Object> hashmap);  
  44. }  

相应的Mapper配置文件

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper  
  3.   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  4.   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  5. <!-- 使用Mapper代理开发 namespace的值与mapper的接口包 -->  
  6. <mapper namespace="com.undergrowth.mybatis.mapper.CityMapper">  
  7.   
  8.     <!-- #{}-表示占位符,对于简单类型、pojo、hashmap 简单类型使用#{value}或者其他名称都可 pojo使用ognl获取值   
  9.         属性名.属性名.. ${}-表示拼接符 ,会导致sql注入 简单类型只能使用${value} pojo使用ognl获取值 -->  
  10.   
  11.     <!-- sql片段 可重用 不用使用where -->  
  12.     <sql id="queryByName">  
  13.         <if test="city!=null">  
  14.             <if test="city.name!=null and city.name!=''">  
  15.                 and city.name like '%${city.name}%'  
  16.             </if>  
  17.         </if>  
  18.     </sql>  
  19.   
  20.     <!-- sql片段 -->  
  21.     <sql id="queryByIds">  
  22.         <if test="ids!=null">  
  23.             <!-- 集合遍历 合成效果 and id in(1,2,34,7) -->  
  24.             <foreach collection="ids" item="user_id" open="and id in("  
  25.                 close=")" separator=",">  
  26.                 #{user_id}  
  27.             </foreach>  
  28.         </if>  
  29.     </sql>  
  30.   
  31.     <select id="fetchByCityById" resultType="com.undergrowth.mybatis.po.City"  
  32.         parameterType="int">  
  33.         select * from city where  
  34.         id = #{id}  
  35.     </select>  
  36.     <!-- 结果集映射 将表的列与pojo的属性进行映射 -->  
  37.     <resultMap type="City" id="queryIdNameCity">  
  38.         <result column="_id" property="id"></result>  
  39.         <result column="_name" property="name"></result>  
  40.     </resultMap>  
  41.   
  42.     <select id="findCityByName" parameterType="string" resultMap="queryIdNameCity">  
  43.         select id _id,name _name from city where name like '%${value}%'  
  44.     </select>  
  45.   
  46.     <select id="findCityCount" parameterType="com.undergrowth.mybatis.po.CityQueryVo"  
  47.         resultType="int">  
  48.         select count(1) from city  
  49.         <where>  
  50.             <!-- where 会自动去掉第一个and include引用之前定义的sql片段 -->  
  51.             <include refid="queryByName"></include>  
  52.             <!-- <if test="city!=null"> <if test="city.name!=null and city.name!=''">   
  53.                 and city.name like '%${city.name}%' </if> </if> -->  
  54.         </where>  
  55.     </select>  
  56.   
  57.     <select id="findCityCountByIds" parameterType="com.undergrowth.mybatis.po.CityQueryVo"  
  58.         resultType="int">  
  59.         select count(1) from city  
  60.         <where>  
  61.             <include refid="queryByIds"></include>  
  62.         </where>  
  63.     </select>  
  64.     <!-- resultType中返回单个pojo和列表pojo的区别在于 Mapper代理对象会根据Mapper接口的方法返回值 来选择使用selectOne还是selectList -->  
  65.     <select id="findCityByHashmap" parameterType="hashmap"  
  66.         resultType="City">  
  67.         select * from city where id=#{id} and name like '%${name}%'  
  68.     </select>  
  69.   
  70.     <!-- 插入语句 -->  
  71.     <insert id="insertCity" parameterType="City" useGeneratedKeys="true"  
  72.         keyProperty="id">INSERT INTO city  
  73.         (  
  74.         Name,  
  75.         CountryCode,  
  76.         District,  
  77.         Population)  
  78.         VALUES  
  79.         (  
  80.         #{name},  
  81.         #{countryCode},  
  82.         #{district},  
  83.         #{population})  
  84.     </insert>  
  85.     <!-- 插入语句 获取自增的主键编号 -->  
  86.     <insert id="insertCityAfter" parameterType="City">  
  87.         <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">  
  88.             select  
  89.             last_insert_id()  
  90.         </selectKey>  
  91.         INSERT INTO city  
  92.         (  
  93.         Name,  
  94.         CountryCode,  
  95.         District,  
  96.         Population)  
  97.         VALUES  
  98.         (  
  99.         #{name},  
  100.         #{countryCode},  
  101.         #{district},  
  102.         #{population})  
  103.     </insert>  
  104.     <!-- 更新 -->  
  105.     <update id="updateCity" parameterType="City">  
  106.         update city set  
  107.         population=#{population} where id=#{id}  
  108.     </update>  
  109.     <!-- 删除 -->  
  110.     <delete id="removeCityById">  
  111.         delete from city where id=#{id}  
  112.     </delete>  
  113. </mapper>  


mybatis的配置文件

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE configuration  
  3.   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  4.   "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  5. <configuration>  
  6.   
  7.     <!-- 先加载properties里面元素 然后resource/url元素的值 最后是parameterType传递的参数值 -->  
  8.     <properties resource="db.properties"></properties>  
  9.     <!-- mybatis运行时全局参数配置 -->  
  10.     <settings>  
  11.         <setting name="cacheEnabled" value="true"></setting>  
  12.     </settings>  
  13.     <!-- 类型别名 -->  
  14.     <typeAliases>  
  15.         <!-- <typeAlias type="com.undergrowth.mybatis.po.City" alias="City"></typeAlias> -->  
  16.         <!-- 批量定义别名 别名与类名一致 大小写均可以 -->  
  17.         <package name="com.undergrowth.mybatis.po" />  
  18.     </typeAliases>  
  19.     <!-- typeHandlers用于jdbc类型和java类型的转化 -->  
  20.     <typeHandlers></typeHandlers>  
  21.   
  22.     <!-- 数据源和事务管理 -->  
  23.     <environments default="development">  
  24.         <environment id="development">  
  25.             <transactionManager type="JDBC" />  
  26.             <dataSource type="POOLED">  
  27.                 <property name="driver" value="${jdbc.driver}" />  
  28.                 <property name="url" value="${jdbc.url}" />  
  29.                 <property name="username" value="${jdbc.username}" />  
  30.                 <property name="password" value="${jdbc.password}" />  
  31.             </dataSource>  
  32.         </environment>  
  33.     </environments>  
  34.     <!-- sql映射 -->  
  35.     <mappers>  
  36.         <mapper resource="sqlmapper/CityMapper.xml" />  
  37.         <!-- 使用此种方式 需要Mapper接口文件与Mapper配置文件同名且位于同一目录 <mapper class=""/> -->  
  38.     </mappers>  
  39.   
  40. </configuration>  

db.properties配置文件

[html] view plaincopy
  1. jdbc.driver=com.mysql.jdbc.Driver  
  2. jdbc.url=jdbc\:mysql\://localhost\:3306/world  
  3. jdbc.username=under  
  4. jdbc.password=under  


log4j.prroperties

[html] view plaincopy
  1. # Global logging configuration  
  2. #\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error  
  3. log4j.rootLogger=DEBUG, stdout  
  4. # Console output...  
  5. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  6. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  7. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n  


两个pojo

[java] view plaincopy
  1. package com.undergrowth.mybatis.po;  
  2.   
  3. public class City {  
  4.   
  5.     private int id;  
  6.     private String name;  
  7.     private String  countryCode;  
  8.     private String district;  
  9.     private int population;  
  10.     public int getId() {  
  11.         return id;  
  12.     }  
  13.     public void setId(int id) {  
  14.         this.id = id;  
  15.     }  
  16.     public String getName() {  
  17.         return name;  
  18.     }  
  19.     public void setName(String name) {  
  20.         this.name = name;  
  21.     }  
  22.     public String getCountryCode() {  
  23.         return countryCode;  
  24.     }  
  25.     public void setCountryCode(String countryCode) {  
  26.         this.countryCode = countryCode;  
  27.     }  
  28.     public String getDistrict() {  
  29.         return district;  
  30.     }  
  31.     public void setDistrict(String district) {  
  32.         this.district = district;  
  33.     }  
  34.     public int getPopulation() {  
  35.         return population;  
  36.     }  
  37.     public void setPopulation(int population) {  
  38.         this.population = population;  
  39.     }  
  40.     @Override  
  41.     public String toString() {  
  42.         return "City [id=" + id + ", name=" + name + ", countryCode="  
  43.                 + countryCode + ", district=" + district + ", population="  
  44.                 + population + "]";  
  45.     }  
  46.       
  47.       
  48. }  


[java] view plaincopy
  1. package com.undergrowth.mybatis.po;  
  2.   
  3. import java.util.List;  
  4.   
  5. /** 
  6.  * 包装用户查询的条件 
  7.  * @author u1 
  8.  * 
  9.  */  
  10. public class CityQueryVo {  
  11.     private City city;  
  12.     private List<Integer> ids;  
  13.       
  14.     public City getCity() {  
  15.         return city;  
  16.     }  
  17.   
  18.     public void setCity(City city) {  
  19.         this.city = city;  
  20.     }  
  21.   
  22.     public List<Integer> getIds() {  
  23.         return ids;  
  24.     }  
  25.   
  26.     public void setIds(List<Integer> ids) {  
  27.         this.ids = ids;  
  28.     }  
  29.       
  30. }  


最终的单元测试

[java] view plaincopy
  1. package com.undergrowth.mybatis.dao;  
  2.   
  3. import java.util.Arrays;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import org.apache.ibatis.session.SqlSession;  
  9. import org.junit.Test;  
  10.   
  11. import com.undergrowth.mybatis.mapper.CityMapper;  
  12. import com.undergrowth.mybatis.po.City;  
  13. import com.undergrowth.mybatis.po.CityQueryVo;  
  14. import com.undergrowth.mybatis.util.SqlSessionUtil;  
  15.   
  16. /** 
  17.  * Dao的测试类 
  18.  *  
  19.  * @author u1 
  20.  * 
  21.  */  
  22. public class CityDao {  
  23.   
  24.     /** 
  25.      * 通过ID查找对象 
  26.      */  
  27.     @Test  
  28.     public void fetchByCityById() {  
  29.         SqlSession sqlSession = null;  
  30.         City city = null;  
  31.         try {  
  32.             sqlSession = SqlSessionUtil  
  33.                     .getSqlSessionFactory("mybatis-conf.xml").openSession();  
  34.             CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);  
  35.             city = cityMapper.fetchByCityById(3);  
  36.             System.out.println(city);  
  37.         } catch (Exception e) {  
  38.             // TODO: handle exception  
  39.             e.printStackTrace();  
  40.         } finally {  
  41.             if (sqlSession != null)  
  42.                 sqlSession.close();  
  43.         }  
  44.   
  45.     }  
  46.   
  47.     /** 
  48.      * 通过模糊查询 
  49.      */  
  50.     @Test  
  51.     public void findCityByName() {  
  52.         SqlSession sqlSession = null;  
  53.         City city = null;  
  54.         try {  
  55.             sqlSession = SqlSessionUtil  
  56.                     .getSqlSessionFactory("mybatis-conf.xml").openSession();  
  57.             // 使用Mapper进行查询 使用接口更加清晰 明了  
  58.             /* 
  59.              * CityMapper cityMapper=sqlSession.getMapper(CityMapper.class); 
  60.              * List<City> citys=cityMapper.findCityByName("und"); 
  61.              * System.out.println(citys); 
  62.              */  
  63.             // 使用sqlsession进行查询  
  64.             List<City> citys = sqlSession.selectList("findCityByName""und");  
  65.             System.out.println(citys);  
  66.         } catch (Exception e) {  
  67.             // TODO: handle exception  
  68.             e.printStackTrace();  
  69.         } finally {  
  70.             if (sqlSession != null)  
  71.                 sqlSession.close();  
  72.         }  
  73.   
  74.     }  
  75.   
  76.     /** 
  77.      * 查找数目 
  78.      */  
  79.     @Test  
  80.     public void findCityCount() {  
  81.         SqlSession sqlSession = null;  
  82.         try {  
  83.             sqlSession = SqlSessionUtil  
  84.                     .getSqlSessionFactory("mybatis-conf.xml").openSession();  
  85.             // 使用Mapper进行查询 使用接口更加清晰 明了  
  86.   
  87.             CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);  
  88.             CityQueryVo vo = new CityQueryVo();  
  89.             City city = new City();  
  90.             city.setName("und");  
  91.             vo.setCity(city);  
  92.             int num = cityMapper.findCityCount(vo);  
  93.             System.out.println(num);  
  94.   
  95.         } catch (Exception e) {  
  96.             // TODO: handle exception  
  97.             e.printStackTrace();  
  98.         } finally {  
  99.             if (sqlSession != null)  
  100.                 sqlSession.close();  
  101.         }  
  102.   
  103.     }  
  104.   
  105.     /** 
  106.      * 通过id集合查找数目 
  107.      */  
  108.     @Test  
  109.     public void findCityCountByIds() {  
  110.         SqlSession sqlSession = null;  
  111.         try {  
  112.             sqlSession = SqlSessionUtil  
  113.                     .getSqlSessionFactory("mybatis-conf.xml").openSession();  
  114.             // 使用Mapper进行查询 使用接口更加清晰 明了  
  115.   
  116.             CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);  
  117.             CityQueryVo vo = new CityQueryVo();  
  118.             City city = new City();  
  119.             city.setName("und");  
  120.             vo.setCity(city);  
  121.             List<Integer> ids = Arrays.asList(123456);  
  122.             vo.setIds(ids);  
  123.             int num = cityMapper.findCityCountByIds(vo);  
  124.             System.out.println(num);  
  125.   
  126.         } catch (Exception e) {  
  127.             // TODO: handle exception  
  128.             e.printStackTrace();  
  129.         } finally {  
  130.             if (sqlSession != null)  
  131.                 sqlSession.close();  
  132.         }  
  133.   
  134.     }  
  135.   
  136.     @Test  
  137.     public void findCityByHashmap() {  
  138.         SqlSession sqlSession = null;  
  139.         try {  
  140.             sqlSession = SqlSessionUtil  
  141.                     .getSqlSessionFactory("mybatis-conf.xml").openSession();  
  142.             // 使用Mapper进行查询 使用接口更加清晰 明了  
  143.   
  144.             CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);  
  145.             Map<String, Object> hashmap=new HashMap<String, Object>();  
  146.             hashmap.put("id""1");  
  147.             hashmap.put("name""");  
  148.             City city=cityMapper.findCityByHashmap(hashmap);  
  149.             System.out.println(city);  
  150.         } catch (Exception e) {  
  151.             // TODO: handle exception  
  152.             e.printStackTrace();  
  153.         } finally {  
  154.             if (sqlSession != null)  
  155.                 sqlSession.close();  
  156.         }  
  157.   
  158.     }  
  159.       
  160.     /** 
  161.      * 插入对象 
  162.      */  
  163.     @Test  
  164.     public void insertCity() {  
  165.         SqlSession sqlSession = null;  
  166.         City city = new City();  
  167.         try {  
  168.             sqlSession = SqlSessionUtil  
  169.                     .getSqlSessionFactory("mybatis-conf.xml").openSession();  
  170.             CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);  
  171.             city.setName("under");  
  172.             city.setCountryCode("AFG");  
  173.             city.setDistrict("china");  
  174.             city.setPopulation(10000);  
  175.             cityMapper.insertCity(city);  
  176.             System.out.println("成功插入");  
  177.         } catch (Exception e) {  
  178.             // TODO: handle exception  
  179.             e.printStackTrace();  
  180.         } finally {  
  181.             if (sqlSession != null)  
  182.                 sqlSession.close();  
  183.         }  
  184.   
  185.     }  
  186.   
  187.       
  188.       
  189.     /** 
  190.      * 获取插入后的id 
  191.      */  
  192.     @Test  
  193.     public void insertCityAfter() {  
  194.         SqlSession sqlSession = null;  
  195.         City city = new City();  
  196.         try {  
  197.             sqlSession = SqlSessionUtil  
  198.                     .getSqlSessionFactory("mybatis-conf.xml").openSession();  
  199.             CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);  
  200.             city.setName("ww");  
  201.             city.setCountryCode("AFG");  
  202.             city.setDistrict("guangzhou");  
  203.             city.setPopulation(10000);  
  204.             cityMapper.insertCityAfter(city);  
  205.             System.out.println("成功插入");  
  206.             System.out.println(city.getId());  
  207.         } catch (Exception e) {  
  208.             // TODO: handle exception  
  209.             e.printStackTrace();  
  210.         } finally {  
  211.             if (sqlSession != null)  
  212.                 sqlSession.close();  
  213.         }  
  214.   
  215.     }  
  216.   
  217.     /** 
  218.      * 修改对象 
  219.      */  
  220.     @Test  
  221.     public void updateCity() {  
  222.         SqlSession sqlSession = null;  
  223.         City city = null;  
  224.         try {  
  225.             sqlSession = SqlSessionUtil  
  226.                     .getSqlSessionFactory("mybatis-conf.xml").openSession();  
  227.             CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);  
  228.             city = cityMapper.fetchByCityById(3);  
  229.             city.setPopulation(10000);  
  230.             System.out.println(city);  
  231.             cityMapper.updateCity(city);  
  232.         } catch (Exception e) {  
  233.             // TODO: handle exception  
  234.             e.printStackTrace();  
  235.         } finally {  
  236.             if (sqlSession != null)  
  237.                 sqlSession.close();  
  238.         }  
  239.   
  240.     }  
  241.   
  242.     /** 
  243.      * 移除对象 
  244.      */  
  245.     @Test  
  246.     public void removeCityById() {  
  247.         SqlSession sqlSession = null;  
  248.         City city = null;  
  249.         try {  
  250.             sqlSession = SqlSessionUtil  
  251.                     .getSqlSessionFactory("mybatis-conf.xml").openSession();  
  252.             CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);  
  253.             cityMapper.removeCityById(4);  
  254.         } catch (Exception e) {  
  255.             // TODO: handle exception  
  256.             e.printStackTrace();  
  257.         } finally {  
  258.             if (sqlSession != null)  
  259.                 sqlSession.close();  
  260.         }  
  261.   
  262.     }  
  263.   
  264. }  


本文主要是对Mapper编程的CRUD进行了学习 sql片段  输入映射  输出映射 进行了学习

0 0
原创粉丝点击