zoukankan      html  css  js  c++  java
  • mybatis第一天学习总结

    mybatis是什么?

    mybatis是一人持久层框架,mybatis是一个不完全的ORM框架。sql语句需要程序员自己去编写,但是mybatis也有映射(输入参数映射、输出结果映射)。

    mybatis入门门槛不高,学习成本低,让程序员把精力放在sql语句上,对sql语句优化非常方便,适用与需求变化较多项目,比如互联网项目。

    mybatis框架执行过程:

    1、配置mybatis的配置文件,SqlMapConfig.xml(名称不固定)

    2、通过配置文件,加载mybatis运行环境,创建SqlSessionFactory会话工厂

             SqlSessionFactory在实际使用时按单例方式。

    3、通过SqlSessionFactory创建SqlSession

             SqlSession是一个面向用户接口(提供操作数据库方法),实现对象是线程不安全的,建议sqlSession应用场合在方法体内。

    4、调用sqlSession的方法去操作数据。

             如果需要提交事务,需要执行SqlSession的commit()方法。

    5、释放资源,关闭SqlSession

    mybatis开发dao的方法:

    1、原始dao 的方法

             需要程序员编写dao接口和实现类

             需要在dao实现类中注入一个SqlSessionFactory工厂。

    2、mapper代理开发方法(建议使用)

             只需要程序员编写mapper接口(就是dao接口)

             程序员在编写mapper.xml(映射文件)和mapper.java需要遵循一个开发规范:

             1、mapper.xml中namespace就是mapper.java的类全路径。

             2、mapper.xml中statement的id和mapper.java中方法名一致。

             3、mapper.xml中statement的parameterType指定输入参数的类型和mapper.java的方法输入 参数类型一致。

             4、mapper.xml中statement的resultType指定输出结果的类型和mapper.java的方法返回值类型一致。

    SqlMapConfig.xml配置文件:可以配置properties属性、别名、mapper加载。。。

    输入映射:

             parameterType:指定输入参数类型可以简单类型、pojo、hashmap。。

             对于综合查询,建议parameterType使用包装的pojo,有利于系统 扩展。

    输出映射:

             resultType:

                       查询到的列名和resultType指定的pojo的属性名一致,才能映射成功。

             reusltMap:

                       可以通过resultMap 完成一些高级映射。

                       如果查询到的列名和映射的pojo的属性名不一致时,通过resultMap设置列名和属性名之间的对应关系(映射关系)。可以完成映射。

                       高级映射:

                                将关联查询的列映射到一个pojo属性中。(一对一)

                                将关联查询的列映射到一个List<pojo>中。(一对多)

    动态sql:(重点)

             if判断(掌握)

             where

             foreach

             sql片段(掌握)

    第一天的代码最终实现:

    Mapper接口文件:

     1 package cn.cuibusimybatis.mapper;
     2 
     3 import java.util.List;
     4 
     5 import cn.cuibusimybatis.po.User;
     6 import cn.cuibusimybatis.po.UserCustom;
     7 import cn.cuibusimybatis.po.UserQueryVo;
     8 
     9 public interface UserMapper {
    10     
    11     //resultmap
    12     public User findUserByResultMap(int id) throws Exception;
    13     
    14     //数量
    15     public int findUserCount(UserQueryVo userQueryVo) throws Exception;
    16     
    17     //综合查询
    18     public List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;
    19     
    20     //根据id查询用户信息
    21     public User findUserById(int id) throws Exception;
    22     
    23     //根据id查询用户信息
    24     //public User findUserById(int id) throws Exception;
    25     
    26     //根据用户名列查询用户列表
    27     public List<User> findUserByName(String name) throws Exception;
    28         
    29     
    30     //添加用户信息
    31     public void insertUser(User user) throws Exception;
    32     
    33     //删除用户信息
    34     public void deleteUser(int id) throws Exception;
    35 }

    mapper映射文件 UserMapper.xml

      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 <!-- 命名空间(sql隔离) -->
      7 <mapper namespace="cn.cuibusimybatis.mapper.UserMapper">
      8 
      9 <!-- 定义sql片段
     10     id:sql片段的唯 一标识
     11     
     12     经验:是基于单表来定义sql片段,这样话这个sql片段可重用性才高
     13     在sql片段中不要包括 where
     14      -->
     15     <sql id="query_user_where">
     16         <if test="userCustom!=null">
     17             <if test="userCustom.sex!=null and userCustom.sex!=''">
     18                 and user.sex = #{userCustom.sex}
     19             </if>
     20             <if test="userCustom.username!=null and userCustom.username!=''">
     21                 and user.username LIKE '%${userCustom.username}%'
     22             </if>
     23             <if test="ids!=null">
     24             <!-- 使用 foreach遍历传入ids
     25             collection:指定输入 对象中集合属性
     26             item:每个遍历生成对象中
     27             open:开始遍历时拼接的串
     28             close:结束遍历时拼接的串
     29             separator:遍历的两个对象中需要拼接的串
     30              -->
     31              <!-- 使用实现下边的sql拼接:
     32               AND (id=1 OR id=10 OR id=16) 
     33               -->
     34             <foreach collection="ids" item="user_id" open="AND (" close=")" separator="or">
     35                 <!-- 每个遍历需要拼接的串 -->
     36                 id=#{user_id}
     37             </foreach>
     38             
     39             <!-- 实现  “ and id IN(1,10,16)”拼接 -->
     40             <!-- <foreach collection="ids" item="user_id" open="and id IN(" close=")" separator=",">
     41                 每个遍历需要拼接的串
     42                 #{user_id}
     43             </foreach> -->
     44             
     45             </if>
     46         </if>
     47     </sql>
     48 
     49 <!-- 定义resultMap
     50     将SELECT id id_,username username_ FROM USER 和User类中的属性作一个映射关系
     51     
     52     type:resultMap最终映射的java对象类型,可以使用别名
     53     id:对resultMap的唯一标识
     54 -->
     55      <resultMap type="user" id="userResultMap">
     56          <!-- id表示查询结果集中唯一标识 
     57          column:查询出来的列名
     58          property:type指定的pojo类型中的属性名
     59          最终resultMap对column和property作一个映射关系 (对应关系)
     60          -->
     61          <id column="id_" property="id"/>
     62          <!-- 
     63          result:对普通名映射定义
     64          column:查询出来的列名
     65          property:type指定的pojo类型中的属性名
     66          最终resultMap对column和property作一个映射关系 (对应关系)
     67           -->
     68          <result column="username_" property="username"/>
     69      </resultMap>
     70     
     71     <!-- 条件查询 -->
     72      <select id="findUserList" parameterType="cn.cuibusimybatis.po.UserQueryVo" resultType="cn.cuibusimybatis.po.UserCustom">
     73         select * from user 
     74         <where>
     75         <!-- 引用sql片段 的id,如果refid指定的id不在本mapper文件中,需要前边加namespace -->
     76         <include refid="query_user_where"></include>
     77         <!-- 在这里还要引用其它的sql片段  -->
     78     </where>
     79     </select> 
     80     
     81     <!-- 条件查询数 -->
     82      <select id="findUserCount" parameterType="cn.cuibusimybatis.po.UserQueryVo" resultType="int">
     83         select count(*) from user where user.sex = #{userCustom.sex} AND user.username like '%${userCustom.username}%'
     84     </select> 
     85 
     86     <!-- 通过select执行数据库查询  #{}表示占位符 id接受输入的参数
     87     resulttype:输出结果所对应的类型
     88     -->
     89     <select id="findUserById" parameterType="int" resultType="cn.cuibusimybatis.po.User">
     90         select * from USER where id=#{id}
     91     </select>
     92     
     93     <!-- resultMap作为返回值类型 -->
     94     <select id="findUserByResultMap" parameterType="int" resultMap="userResultMap">
     95         select id id_,username username_ from USER where id=#{value}
     96     </select>
     97     
     98     <!-- 根据用户名查询 
     99         ${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。
    100         使用${}拼接sql,引起 sql注入
    101         ${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value
    102     -->
    103     
    104     <select id="findUserByName" parameterType="java.lang.String" resultType="cn.cuibusimybatis.po.User">
    105         select * from user where username like '%${value}%'
    106     </select>
    107     
    108     <!-- 添加用户
    109     parameterType:指定输入的类型是pojo
    110     select LAST_INSERT_ID() 得到刚刚插入的主键,仅适用于自增主键
    111      -->
    112     <insert id="insertUser" parameterType="cn.cuibusimybatis.po.User">
    113         <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
    114             select LAST_INSERT_ID()
    115         </selectKey>
    116         insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
    117     </insert>
    118     
    119     <!-- 
    120         使用mysql的uuid()生成主键
    121         执行过程:
    122         首先通过uuid()得到主键,将主键设置到user对象的id属性中
    123         其次在insert执行时,从user对象中取出id属性值
    124          -->
    125         <!--  <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
    126             SELECT uuid()
    127         </selectKey>
    128         insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address}) 
    129         -->
    130         
    131     <!-- 删除用户 -->
    132     <delete id="deleteUser" parameterType="java.lang.Integer">
    133         delete from user where id=#{id}
    134     </delete>
    135     
    136     <!-- 根据id更新用户
    137     分析:
    138     需要传入用户的id
    139     需要传入用户的更新信息
    140     parameterType指定user对象,包括 id和更新信息,注意:id必须存在
    141     #{id}:从输入 user对象中获取id属性值
    142      -->
    143     <update id="updateUser" parameterType="cn.cuibusimybatis.po.User">
    144         update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} 
    145          where id=#{id}
    146     </update>
    147 </mapper>

    包装类型类  UserQueryVo:

    
    
     1 package cn.cuibusimybatis.po;
     2 
     3 import java.util.List;
     4 
     5 /**
     6  *包装类型
     7  */
     8 public class UserQueryVo {
     9     
    10     
    11     //在这里包装所有的查询条件
    12 
    13     //传入多个id
    14     private List<Integer> ids;
    15     public List<Integer> getIds() {
    16         return ids;
    17     }
    18     public void setIds(List<Integer> ids) {
    19         this.ids = ids;
    20     }
    21     
    22     //用户的查询条件
    23     private UserCustom userCustom;
    24     public UserCustom getUserCustom() {
    25         return userCustom;
    26     }
    27     public void setUserCustom(UserCustom userCustom) {
    28         this.userCustom = userCustom;
    29     }
    30     
    31 }
    
    

    核心配置文件 SqlMapConfig:

     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配置文件 -->
     8     <properties resource="db.properties">
     9     <!--properties中还可以配置一些属性名和属性值  -->
    10     <!-- <property name="jdbc.driver" value=""/> -->
    11     </properties>
    12     <!-- 别名定义 -->
    13     <typeAliases>
    14         <!-- <typeAlias type="cn.cuibusimybatis.po.User" alias="user"/> -->
    15         <!-- 批量别名定义 
    16         指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以)
    17         -->
    18         <package name="cn.cuibusimybatis.po"/>
    19         
    20     </typeAliases>
    21     <!-- 和spring整合后 environments配置将废除-->
    22     <environments default="development">
    23         <environment id="development">
    24         <!-- 使用jdbc事务管理-->
    25             <transactionManager type="JDBC" />
    26         <!-- 数据库连接池-->
    27             <dataSource type="POOLED">
    28                 <property name="driver" value="${jdbc.driver}" />
    29                 <property name="url" value="${jdbc.url}" />
    30                 <property name="username" value="${jdbc.username}" />
    31                 <property name="password" value="${jdbc.password}" />
    32             </dataSource>
    33         </environment>
    34     </environments>
    35     
    36     <!-- 加载映射文件 -->
    37     <mappers>
    38         <!-- <mapper resource="sqlmap/User.xml"/> -->
    39         <!-- <mapper resource="mapper/UserMapper.xml"/> -->
    40         
    41         <!-- 通过mapper接口加载单个 映射文件
    42         遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
    43         上边规范的前提是:使用的是mapper代理方法
    44          -->
    45         <!-- <mapper class="cn.cuibusimybatis.mapper.UserMapper"/> -->
    46         <!-- 批量加载mapper
    47         指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载
    48         遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
    49         上边规范的前提是:使用的是mapper代理方法
    50          -->
    51         <package name="cn.cuibusimybatis.mapper"/>
    52         
    53     </mappers>
    54 </configuration>
  • 相关阅读:
    Server Application Unavailable 解决办法 (转)
    SQL SERVER:分割函数 split
    Win32汇编_基础
    Win32汇编_异常_筛选器
    创建进程常用函数
    内存常用函数
    桃花庵歌
    文天祥的诗
    Socket I/O模型全接触
    函数指针的神奇
  • 原文地址:https://www.cnblogs.com/cuibin/p/6815800.html
Copyright © 2011-2022 走看看