MyBatis 总结一下--源自技术

框架简介:(来源百度百科)

iBATIS一词来源于“internet”和“abatis”的组合,是一个由Clinton Begin在2002年发起的开放源代码项目。

于2010年6月16号被谷歌托管,改名为MyBatis。2013年11月迁移到Github。

资源下载

教程

http://mybatis.github.io/mybatis-3/zh/dynamic-sql.html

Mybatis jar包下载

http://www.mvnrepository.com/artifact/org.mybatis/mybatis/3.3.0

基本API示例

1.创建配置文件(sqlMapConfig.xml)

[html]  view plain  copy
  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.     <environments default="development">  
  8.         <environment id="development">  
  9.             <transactionManager type="JDBC"/>  
  10.             <dataSource type="POOLED">  
  11.                 <property name="driver" value="com.mysql.jdbc.Driver"/>  
  12.                 <property name="url" value="jdbc:mysql://localhost:3306/cs?characterEncoding=UTF-8"/>  
  13.                 <property name="username" value="root"/>  
  14.                 <property name="password" value="root"/>  
  15.             </dataSource>  
  16.         </environment>  
  17.     </environments>  
  18.   
  19.     <!-- 映射配置文件  -->  
  20.     <mappers>  
  21.         <mapper resource="Students.xml"/>  
  22.     </mappers>  
  23. </configuration>  


2.获取MyBatis sql会话对象

[java]  view plain  copy
  1. public static SqlSession getSession() throws IOException{  
  2.     String cf = "sqlMapConfig.xml";  
  3.     InputStream inputStream = Resources.getResourceAsStream(cf);  
  4.     SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);  
  5.     return  sqlSessionFactory.openSession();  
  6. }  

3.创建映射配置文件(Students.xml)

[java]  view plain  copy
  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.   
  6. <!-- 命名空间用于查找  -->  
  7. <mapper namespace="com.wwq.test.Students">  
  8. <!-- 复用的公共部分 -->  
  9. <sql id="cols">  
  10.      id,name,age,pass,score         
  11. </sql>  
  12. <sql id="table">  
  13. <span style="white-space:pre">    </span>students  
  14. </sql>  
  15. <sql id="inserVals">  
  16. #{id, jdbcType=INTEGER},  
  17. #{name, jdbcType=VARCHAR},  
  18. #{age, jdbcType=INTEGER},  
  19. #{pass, jdbcType=BOOLEAN},  
  20. #{score, jdbcType=DOUBLE}  
  21. </sql>  
  22. <sql id="updateVals">  
  23. set name = #{name, jdbcType=VARCHAR},  
  24. age = #{age, jdbcType=INTEGER},  
  25. pass = #{pass, jdbcType=BOOLEAN},  
  26. score = #{score, jdbcType=DOUBLE}  
  27. </sql>  
  28. <!-- 查询 -->  
  29. <select id="findAll_stu" resultType="com.wwq.test.bean.Students">  
  30.     SELECT <include refid="cols"/> FROM  <include refid="table"/>  
  31. </select>  
  32. <!-- 插入 -->  
  33. <insert id="insert_stu" useGeneratedKeys="true" keyProperty="id">  
  34.       INSERT INTO <include refid="table"/> ( <include refid="cols"/> ) VALUES ( <include refid="inserVals" />);  
  35. </insert>  
  36. <!-- 修改 -->  
  37. <update id="update_stu">  
  38.       UPDATE <include refid="table"/> <include refid="updateVals"/>  
  39. </update>  
  40. <!-- 删除 -->  
  41. <delete id="delete_stu" parameterType="com.wwq.test.bean.Students">  
  42.       DELETE FROM <include refid="table"/>  
  43. </delete>  
  44. </mapper>  

4.创建数据模型Bean

[java]  view plain  copy
  1. public class Students{  
  2.     private Integer id;  
  3.     private String name;  
  4.     private Integer age;  
  5.     private Boolean pass;  
  6.     private Double score;  
  7.     public Integer getId() {  
  8.         return id;  
  9.     }  
  10.     public void setId(Integer id) {  
  11.         this.id = id;  
  12.     }  
  13.     public String getName() {  
  14.         return name;  
  15.     }  
  16.     public void setName(String name) {  
  17.         this.name = name;  
  18.     }  
  19.     public Integer getAge() {  
  20.         return age;  
  21.     }  
  22.     public void setAge(Integer age) {  
  23.         this.age = age;  
  24.     }  
  25.     public Boolean getPass() {  
  26.         return pass;  
  27.     }  
  28.     public void setPass(Boolean pass) {  
  29.         this.pass = pass;  
  30.     }  
  31.     public Double getScore() {  
  32.         return score;  
  33.     }  
  34.     public void setScore(Double score) {  
  35.         this.score = score;  
  36.     }  
  37. }  

5.调用相应的API

[java]  view plain  copy
  1. /*保存:返回影响的行数*/  
  2. public static void save() throws IOException, InterruptedException{  
  3.     Students llj = new Students("李连杰"45true92.5);  
  4.     SqlSession session = getSession();  
  5.     int number = session.insert("insert_stu",llj);  
  6.     System.out.println(String.format("主键:%1$s", llj.getId()));  
  7.     System.out.println(String.format("插入的行数:%1$s", number));  
  8.     session.commit();  
  9. }  
  10.   
  11. /*删除:返回影响的行数*/  
  12. public static void del()throws IOException, InterruptedException{  
  13.     SqlSession session = getSession();  
  14.     Students stu = new Students();  
  15.     stu.setId(15);  
  16.     int number = session.delete("delete_stu",stu);  
  17.     session.commit();  
  18.     System.out.println(String.format("删除的行数:%1$s", number));  
  19. }  
  20.   
  21. /*修改:返回影响的行数*/  
  22. public static void update()throws IOException,InterruptedException{  
  23.     Students stu = new Students(true);  
  24.     SqlSession session = getSession();  
  25.     int number = session.update("update_stu",stu);  
  26.     session.commit();  
  27.     System.out.println(String.format("更新的行数:%1$s", number));  
  28. }  
  29.   
  30. /*没有记录返回,一个空的集合(不是null)*/  
  31. public static List<Students> findAll() throws IOException, InterruptedException{  
  32.     SqlSession session = getSession();  
  33.     List<Students> stus = session.selectList("findAll_stu");  
  34.     System.out.println(stus);  
  35.     return stus;  
  36. }  
  37.   
  38. /*使用selectOne API查询,结果多条会报异常:Expected one result (or null) to be returned by selectOne(), but found: 2*/  
  39. public static Students findOne() throws IOException, InterruptedException{  
  40.     SqlSession session = getSession();  
  41.     Students stu = session.selectOne("findAll_stu");  
  42.     return stu;  
  43. }  
  44.   
  45. /*RowBounds:指定检索范围,他是在查询结果之上再次进行范围筛选*/  
  46. public static List<Students> findBounds()throws IOException, InterruptedException{  
  47.     SqlSession session = getSession();  
  48.     RowBounds rowBounds = new RowBounds(02);  
  49.     List<Students> stus = session.selectList("findAll_stu"null, rowBounds);  
  50.     System.out.println(stus);  
  51.     return stus;  
  52. }  
  53.   
  54. /*selectMap:将返回的列表转换成以某列值为key的map*/  
  55. public static Map<Integer, Students> findMap()throws IOException, InterruptedException{  
  56.     SqlSession session = getSession();  
  57.     Map<Integer, Students> selectMap = session.selectMap("findAll_stu""id");  
  58.     System.out.println(selectMap);  
  59.     return selectMap;  
  60. }  


动态SQL示例

1.增加动态SQL映射配置

[html]  view plain  copy
  1. <!-- ############### 动态SQL ############### -->  
  2. <!-- if -->  
  3. <delete id="delete_dynamic_if" parameterType="java.lang.Integer">  
  4.     DELETE FROM <include refid="table"/> WHERE   
  5.     <if test="id!=null and id!=''"> id = #{id,jdbcType=INTEGER}</if>  
  6.     <if test="name!=null and name!=''"> AND name LIKE #{id,jdbcType=INTEGER}</if>  
  7. </delete>  
  8. <!-- choose -->  
  9. <delete id="delete_dynamic_choose" parameterType="java.lang.Integer">  
  10.     DELETE FROM <include refid="table"/> WHERE  
  11.     <choose>  
  12.         <when test="score>60">age < 25</when>  
  13.         <otherwise>age > 25 </otherwise>  
  14.     </choose>  
  15. </delete>  
  16. <!-- where -->  
  17. <select id="delete_dynamic_where" parameterType="java.lang.Integer">  
  18.     SELECT * FROM <include refid="table"/>  
  19.     <where>  
  20.         <if test="id!=null and id!=''"> id = #{id,jdbcType=INTEGER}</if>  
  21.         <if test="name!=null and name!=''"> AND name LIKE #{id,jdbcType=INTEGER}</if>  
  22.     </where>  
  23. </select>  
  24. <!-- set -->  
  25. <update id="delete_dynamic_set">  
  26.     UPDATE <include refid="table"/>  
  27.     <set>  
  28.         <if test="name!=null and name!=''">name = #{name, jdbcType=VARCHAR},</if>  
  29.         <if test="age!=null and age!=''">age = #{age, jdbcType=INTEGER},</if>  
  30.         <if test="pass!=null and pass!=''">pass = #{pass, jdbcType=BOOLEAN},</if>  
  31.         <if test="pass!=null and pass!=''">score = #{score, jdbcType=DOUBLE}</if>  
  32.     </set>  
  33. </update>  
  34. <!-- trim -->  
  35. <delete id="delete_dynamic_trim">  
  36.     DELETE FROM <include refid="table"/>  
  37.     <trim prefix="WHERE" prefixOverrides="AND | OR ">  
  38.         <if test="name!=null and name!=''">AND name = #{name, jdbcType=VARCHAR}</if>  
  39.         <if test="age!=null and age!=''">AND age = #{age, jdbcType=INTEGER}</if>  
  40.         <if test="pass!=null and pass!=''">OR pass = #{pass, jdbcType=BOOLEAN}</if>  
  41.         <if test="pass!=null and pass!=''">AND score = #{score, jdbcType=DOUBLE}</if>  
  42.     </trim>  
  43. </delete>  
  44. <update id="delete_dynamic_trim2">  
  45.     UPDATE <include refid="table"/>  
  46.     <trim prefix="SET" suffix="," suffixOverrides=",">  
  47.         <if test="name!=null and name!=''">name = #{name, jdbcType=VARCHAR}</if>  
  48.         <if test="age!=null and age!=''">age = #{age, jdbcType=INTEGER}</if>  
  49.         <if test="pass!=null and pass!=''">pass = #{pass, jdbcType=BOOLEAN}</if>  
  50.         <if test="pass!=null and pass!=''">score = #{score, jdbcType=DOUBLE}</if>  
  51.     </trim>  
  52. </update>  
  53. <!-- foreach:集合取值形参必须是list -->  
  54. <select id="findAll_dynamic_foreach" resultType="com.wwq.test.bean.Students">  
  55.     SELECT * FROM <include refid="table"/>  
  56.     <if test="list!=null and list.size() > 0">  
  57.         WHERE id IN  
  58.         <foreach item="stu" index="index" collection="list"  open="(" separator="," close=")">  
  59.             #{stu.id}  
  60.         </foreach>  
  61.     </if>  
  62. </select>  

2.调用相应的API

[java]  view plain  copy
  1. /*动态sql:foreach*/  
  2. public static List<Students> findAllDynamicForeach()throws IOException, InterruptedException{  
  3.     SqlSession session = getSession();  
  4.     List<Students> stus = new ArrayList<Students>();  
  5.     stus.add(new Students(16));  
  6.     stus.add(new Students(18));  
  7.     List<Students> ruts = session.selectList("findAll_dynamic_foreach",stus);  
  8.     return ruts;  
  9. }  


关联映射示例

1.在数据模型Bean中增加关联实体。

[java]  view plain  copy
  1. public class Students{  
  2.     .......  
  3.     private Role role;  
  4.     private List<ClassAndGrade> cgs;  
  5.     public List<ClassAndGrade> getCgs() {  
  6.         return cgs;  
  7.     }  
  8.     public void setCgs(List<ClassAndGrade> cgs) {  
  9.         this.cgs = cgs;  
  10.     }  
  11.     public Role getRole() {  
  12.         return role;  
  13.     }  
  14.     public void setRole(Role role) {  
  15.         this.role = role;  
  16.     }  
  17.     ........  
  18. }  

2.增加映射文件

[html]  view plain  copy
  1. <!-- 关联嵌套查询  -->  
  2. <resultMap id="resStu" type="com.wwq.test.bean.Students">  
  3.   <association property="role" column="role_id" javaType="com.wwq.test.bean.Role" select="selectRole"/>  
  4. </resultMap>  
  5. <select id="find_ResStu" resultMap="resStu">  
  6.     SELECT * FROM students  
  7. </select>  
  8. <select id="selectRole" resultType="com.wwq.test.bean.Role">  
  9.     SELECT * FROM role WHERE id = #{id}  
  10. </select>  
  11.   
  12. <!-- 关联嵌套结果  -->  
  13. <resultMap id="resStuResults" type="com.wwq.test.bean.Students">  
  14.     <association property="role" javaType="com.wwq.test.bean.Role">  
  15.         <id property="id" column="role_id"/>  
  16.         <result property="name" column="role_name"/>  
  17.     </association>  
  18. </resultMap>  
  19. <select id="find_ResStu_results" resultMap="resStuResults">  
  20. SELECT s.id,s.name,age,pass,score,role_id,r.name role_name   
  21. FROM students s LEFT JOIN role r ON s.role_id = r.id;  
  22. </select>  
  23.   
  24. <!-- 集合的嵌套查询 -->  
  25. <resultMap id="resStuColl" type="com.wwq.test.bean.Students">  
  26.     <collection property="cgs" javaType="ArrayList" column="id" ofType="com.wwq.test.bean.ClassAndGrade" select="find_cgs_select"/>  
  27. </resultMap>  
  28. <select id="find_Res_Stu_Coll" resultMap="resStuColl">  
  29.     SELECT * FROM students  
  30. </select>  
  31. <select id="find_cgs_select" resultType="com.wwq.test.bean.ClassAndGrade">  
  32. SELECT * FROM classandgrade  cg  
  33. LEFT JOIN stu_cg sc ON cg.id = sc.cg_id  
  34. WHERE sc.stu_id = #{id};  
  35. </select>  
  36. <!-- 集合的嵌套结果 -->  
  37. <resultMap id="resStuResultsColl" type="com.wwq.test.bean.Students">  
  38.     <collection property="cgs" ofType="com.wwq.test.bean.ClassAndGrade" >  
  39.         <result column="cg_id" property="id"/>  
  40.         <result column="cg_name" property="name"/>  
  41.     </collection>  
  42. </resultMap>  
  43. <select id="find_Res_Stu_Coll_Results" resultMap="resStuResultsColl">  
  44. SELECT s.id,s.name,age,pass,score,role_id,r.name role_name,cg.id as cg_id,cg.name as cg_name  
  45. FROM students s   
  46. LEFT JOIN role r ON s.role_id = r.id  
  47. LEFT JOIN stu_cg sc ON sc.stu_id = s.id  
  48. LEFT JOIN classandgrade cg ON cg.id = sc.cg_id;  
  49. </select>  


打印映射的SQL

1.导入Log4j的jar包。

下载Log4j

2.编写Log4j配置文件

[plain]  view plain  copy
  1. # Global logging configuration  
  2. log4j.rootLogger=ERROR, stdout  
  3. # MyBatis logging configuration...  
  4. log4j.logger.com.wwq.test.Students=TRACE  
  5. # Console output...  
  6. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  7. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  8. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n  


完整示例:MyBatis 练习 (http://download.csdn.net/detail/javamr_wwq/9246761)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值