Mybatis总结

来源:互联网 发布:即时通讯软件怎么开发 编辑:程序博客网 时间:2024/06/05 03:57

整理mybatis思路:
1.代码中通过流的方式读取mybatis的配置文件,
String resource = “SqlMapConfig.xml”;
//通过流将核心配置文件读取进来
InputStream inputStream = Resources.getResourceAsStream(resource);
//通过核心配置文件输入流来创建会话工厂
private SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
2.定义映射器:编写接口mapper和配置文件mapper.xml并且要放在同一个包下面,具体的配置规则在下面的代码中体现。
3.在mybatis的配置文件中SqlMapConfig.xml中引入mapper.xml
4.具体的配置规则如下例子:
4.1接口:
/**
* 官方推荐使用这种方式
* @author Administrator
*
*/
public interface UserMapper {

public User findUserById(Integer id);//动态代理形式中,如果返回结果集问List,那么mybatis会在生成实现类的使用会自动调用selectList方法public List<User> findUserByUserName(String userName);public void insertUser(User user);public List<User> findUserbyVo(QueryVo vo);public Integer findUserCount();public List<User> findUserByUserNameAndSex(User user);public List<User> findUserByIds(QueryVo vo);

// public List findOrdersAndUser1() ;

public List<Orders> findOrdersAndUser2();public List<User> findUserAndOrders();
}

配置文件:

<?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">
<!--
mapper接口代理实现编写规则:
    namespace:用于隔离sql
    1. 映射文件中namespace要等于接口的全路径名称
    2. 映射文件中sql语句id要等于接口的方法名称
    3. 映射文件中传入参数类型要等于接口方法的传入参数类型
    4. 映射文件中返回结果集类型要等于接口方法的返回值类型
 -->
 
<mapper namespace="com.itheima.po.UserMapper">

    <!-- sql:封装sql条件,封装以后可以调用
        id:是这个条件的唯一标示
    
    -->
    <sql id="user_Where">
    
    <!-- where标签作用:
                会自动向sql语句中添加where关键字
                会去掉第一个条件的and关键字
             -->
        <where>
            <if test="username != null and username!=''">
                username like '%${username}%'
            </if>
            <if test="sex !=null and sex!=''">
                and sex=#{sex}
            </if>
        </where>
    </sql>
    <!--
        id:sql语句唯一标识
    parameterType:指定传入参数类型
    resultType:返回结果集类型
    #{}占位符:起到占位作用,如果传入的是基本类型(string,long,double,int,boolean,float等),那么#{}中的变量名称可以随意写.
    
     -->
    <select id="findUserById" parameterType="int" resultType="com.itheima.pojo.User">
        select * from user where id=#{id};
    </select>
    
    <!--
    如果返回结果为集合,可以调用selectList方法,这个方法返回的结果就是一个集合,所以映射文件中应该配置成集合泛型的类型
    ${}拼接符:字符串原样拼接,如果传入的参数是基本类型(string,long,double,int,boolean,float等),那么${}中的变量名称必须是value
    注意:拼接符有sql注入的风险,所以慎重使用
     -->
    <select id="findUserByUserName" parameterType="string" resultType="user">
        select * from user where username like '%${value}%'
    </select>
    
    <!--
    #{}:如果传入的是pojo类型,那么#{}中的变量名称必须是pojo中对应的属性.属性.属性.....
    如果要返回数据库自增主键:可以使用select LAST_INSERT_ID()
     -->
    <insert id="insertUser" parameterType="com.itheima.pojo.User" >
        <!-- 执行 select LAST_INSERT_ID()数据库函数,返回自增的主键
        keyProperty:将返回的主键放入传入参数的Id中保存.
        order:当前函数相对于insert语句的执行顺序,在insert前执行是before,在insert后执行是AFTER
        resultType:id的类型,也就是keyproperties中属性的类型
        -->
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        </selectKey>
        insert into user (username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
    </insert>
    
    <select id="findUserbyVo" parameterType="com.itheima.po.QueryVo" resultType="com.itheima.po.User">
        select * from user where username like '%${user.username}%' and sex=#{user.sex};
    </select>
    
    <!-- 只有返回结果为一行一列的时候,那么返回值类型才可以指定成基本类型 -->
    <select id="findUserCount" resultType="java.lang.Integer">
        select count(*) from user
    </select>
    
    <!-- 动态sql -->
    <select id="findUserByUserNameAndSex" parameterMap="com.itheima.pojo.User" resultType="com.itheima.pojo.User">
        
        select * from user ;
        <include refid="user_Where"></include>
    
    </select>
    
    <select id="findUserByIds" parameterType="com.itheima.pojo.QueryVo" resultType="com.itheima.pojo.User">
        select * from user where id in(1,16,25,26);
        <where>
            <if test="ids !=null">
                <!--
                    foreach:循环传入的集合参数
                    collection:传入的集合的变量名称
                    item:每次循环将循环出的数据放入这个变量中
                    open:循环开始拼接的字符串
                    close:循环结束拼接的字符串
                    separator:循环中拼接的分隔符
                  -->
                <foreach collection="ids" item="id" open="id in(" close=")" separator="," >
                #{id}
                </foreach>
            </if>
        </where>
    </select>
    
    <!-- 一对一手动映射:mybatis官方推荐使用 -->
    <!-- resultMap需要自己定义,因为查询的是两张表中的数据 -->
    <!--
        type:将查询出来的数据放入到这个指定的对象当中
        id:resultMap的唯一标示
        注意:手动映射需要指定数据库表中的字段名和pojo中属性名称的对应关系
     -->
    <resultMap type="com.itheima.po.Orders" id="orderAndUserResultMap">
        <!-- id标签指明主键的对应关系
            column:数据库表的主键
            property:java pojo中的属性名称
        -->
        <id column="id" property="id"/>
        <!-- result:标签指定非主键字段的对应关系 -->
        <result column="user_id" property="userId"/>
        <result column="number" property="number"/>
        <result column="createtime" property="createtime"/>
        <result column="note" property="note"/>
        
        <!-- 还需要执行另一张表中的对应关系 -->
        <!--
            这个标签制定了单个对象的对应关系
         -->
        <association property="user" javaType="com.itheima.pojo.User">
            <id column="uid" property="id"/>
            <result column="username" property="username"/>
            <result column="birthday" property="birthday"/>
            <result column="sex" property="sex"/>
            <result column="address" property="address"/>
        </association>
    </resultMap>
    <select id="findOrdersAndUser2" resultMap="orderAndUserResultMap">
        select a.* ,b.id uid,username,birthday,sex,address from orders a, user b where a.user_id=b.id;
    </select>
    
    <resultMap type="com.itheima.pojo.User" id="userAndOrdersResultMap">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="birthday" property="birthday"/>
        <result column="sex" property="sex"/>
        <result column="address" property="address"/>
        
        <!-- 指定对应的集合对象关系映射
        property:将数据放入User对象中的ordersList属性中
        ofType:指定ordersList属性的泛型类型
         -->
        <collection property="ordersList" ofType="com.itheima.pojo.Orders">
        
            <id column="oid" property="id"/>
            <result column="user_id" property="userId"/>
            <result column="number" property="number"/>
            <result column="createtime" property="createtime"/>
        </collection>
    </resultMap>
    
    <select id="findUserAndOrders" resultMap="userAndOrdersResultMap">
        select a.*,b.id oid ,user_id,number,createtime from user a, orders b where a.id=b.user_id;
    </select>
    
</mapper>


简单的配置例子:

<?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">
<!-- namespace 用于隔离sql,一般为接口的全限定名 -->
<mapper namespace="test">
    <!--
        根据用户id查询用户
        id:sql语句的唯一表示
        parameterType:制定了出入参数的类型
        resultType:返回的结果集类型
        #{}:起到占位符的作用,如果传入的是基本类型( string ,long ,double,int,boolean,float),那么#{} 中的变量可以随意写。
        
     -->
    <select id="findUserById" parameterType="java.lang.Integer" resultType="com.itheima.pojo.User">
        select * from user where id=#{id};
    </select>
    
    <!--
        通过用户名查询用户
        ${}: 字符串原样拼接,如果传入参数的是基本类型(string ,long, double,int ,boolean,float)那么${}中的变量名必须是value
        注意:拼接符有sql注入风险,所以慎用
    
     -->
    <select id="findUserByUserName" parameterType="java.lang.String" resultType="com.itheima.pojo.User">
        select * from user where username like '%${value}%'
    </select>
    
    <!--
         插入
        #{}:如果传入的参数为pojo类型,那么里面的参数必须写成pojo的属性.属性
        如果要返回数据库的自增的主键可以使用:select LAST_INSERT_ID()
        
    
    
     -->
     <insert id="" parameterType="">
        <!--
            keyProperty:将返回的主键放入传入的参数id中保存
            order:当前函数相对于insert语句的执行顺序,如果在insert之前泽勇before,如果在之后泽勇after
            resultType:id的类型也就是keyProperty的类型
         -->
         <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.Integer">
              select LAST_INSERT_ID();
         </selectKey>
         insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address});
     </insert>
    
     <!-- 其中paramterType用了内置的别名  -->
     <delete id="delUserById" parameterType="int">
         delete from user where id=#{id};
     </delete>
    
     <!-- 更新
      -->
     <update id="updateUserById" parameterType="com.itheima.pojo.User">
         
         update user set username=#{username} where id=#{id};
    
     </update>
    
</mapper>



原创粉丝点击