mybatis_2

mybatis工具类

public class MybatisUtils {

    private  static  SqlSessionFactory sqlSessionFactory;
    static {
         try {
             //使用mybatis第一步:获取sqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //既然有了sqlsessionfactory,我们就可以从中获取sqlsession的实例了。
    //sqlsession完全包含了面向数据库执行sql命令所需的所有方法。
    public  static SqlSession getSqlSession(){
        return  sqlSessionFactory.openSession();
    }
}

insert,delete,update

  • 对应的curd标签,没有resultType,接口返回值类型是int(Integer)
  • insert标签可能需要得到新增记录id,useGeneratedKeys=“true” keyProperty=“uid”
  • 需要手动commit

resultMap结果映射标签

  • 对查询结果做映射处理
<resultMap id="aa" type="com.javasm.entity.Goods">
        <id column="gid" property="gid"></id> //一般默认都把id配上
        <result column="goodsColor" property="gcolor"></result>
</resultMap>
  • 对象关系映射
    • association与collection选择性的使用,自己写独立的查询方法也可以实现。
    • association与collection两个使用方法:
      • 拆分多次单表查询,通过select属性指定二次查询的位置。
      • 一次多表连接查询,通过做字段映射把不同的字段映射的不同的对象中。
  • 1-1、1-N
    • 情景:查询用户时,把该用户下的订单信息查询出来。
// 两种方式
// 1、 执行两条sql语句
// 实体类
public class Sysuser {
    private Integer uid;
    private String uname;
    private String uphone;
    private String upwd;
    private String createTime;
    private List<GoodsOrder> ordersList; // 聚合关系
......
}
// mapper接口
public Sysuser selectUserOrdersByKey(int key);
//查询订单信息,仅查询订单信息
public List<GoodsOrder> selectOrderByUserId(int uid);

// mapper文件
<select id="selectUserOrdersByKey" resultMap="userRM" parameterType="int">
  select * from sysuser where uid=#{uid}
</select>

<resultMap id="userRM" type="sysuser">
    <id column="uid" property="uid"></id>
    <result column="uname" property="uname"></result>
    <result column="uphone" property="uphone"></result>
    <result column="upwd" property="upwd"></result>
    <result column="create_time" property="createTime"></result>
    <!--1-N映射,N-N-->
    <collection property="ordersList" ofType="GoodsOrder" column="uid" select="com.javasm.mapper.GoodsOrderMapper.selectOrderByUserId"></collection>
</resultMap>

<select id="selectOrderByUserId"  resultType="goodsOrder">
    select * from goodsOrder where uid=#{uid}
</select>

// 2、多表关联查询
// mapper接口
public Sysuser selectUserOrdersByKey2(int key);
// mapper文件
<select id="selectUserOrdersByKey2" resultMap="userRM2" parameterType="int">
  select u.*,o.oid,o.otime,o.oprice from sysuser u,goodsOrder o where o.uid=u.uid and u.uid=#{uid}
</select>

<resultMap id="userRM2" type="sysuser">
    <id column="uid" property="uid"></id>
    <result column="uname" property="uname"></result>
    <result column="uphone" property="uphone"></result>
    <result column="upwd" property="upwd"></result>
    <result column="create_time" property="createTime"></result>
    <!--1-N映射,N-N-->
    <collection property="ordersList" ofType="GoodsOrder">
        <id column="oid" property="oid"></id>
        <result column="otime" property="otime"></result>
        <result column="oprice" property="oprice"></result>
    </collection>
</resultMap>
  • N-1、N-N
    • 情景:查询订单信息以及订单的所属人信息
// 两种方式
// 1、 执行两条sql语句
// 实体类
public class GoodsOrder {
    private String oid;
    private String otime;
    private Double oprice;
    private Sysuser suser;//订单所有人
......
}
// mapper接口
//查询订单信息以及订单的所属人信息
public GoodsOrder selectOrderAndUserByKey(String oid);
public Sysuser selectUserByKey(int key);

// mapper文件
<!--把多表查询拆分两次的单表查询,推荐使用单表查询-->
<select id="selectOrderAndUserByKey" parameterType="String" resultMap="aa">
    select * from goodsOrder where oid=#{oid}
</select>

<resultMap id="aa" type="goodsOrder">
    <id column="oid" property="oid"></id>
    <result column="oprice" property="oprice"></result>
    <result column="otime" property="otime"></result>
    <!--<result column="uid" property="suser.uid"></result>-->
    <!--association:做对象1-1,N-1关系映射 -->
    <!--把uid列的值作为参数,传入select所指向的查询语句,返回结果是javaType,赋值给goodsOrder的suser属性-->
    <association property="suser" javaType="Sysuser" column="uid" select="com.javasm.mapper.SysuserMapper.selectUserByKey"></association>
</resultMap>
// sql片的拼接,提高复用性
<sql id="userFields">
    uid,uname,uphone,upwd,create_time
</sql>

<select id="selectUserByKey" resultType="sysuser" parameterType="int" >
  select
   <include refid="userFields"></include>
   from sysuser where uid=#{uid}
</select>


// 2、多表关联查询
// mapper接口
public GoodsOrder selectOrderAndUserByKey2(String oid);
// mapper文件
<!--做表连接查询,把需要的数据全部查询出来-->
<select id="selectOrderAndUserByKey2" parameterType="String" resultMap="aa2">
    select o.*,u.uname,u.uphone,u.upwd,u.create_time from goodsOrder o,Sysuser u where o.uid=u.uid and o.oid=#{oid}
</select>

<resultMap id="aa2" type="goodsOrder">
    <id column="oid" property="oid"></id>
    <result column="oprice" property="oprice"></result>
    <result column="otime" property="otime"></result>
    <association property="suser" javaType="Sysuser">
        <id column="uid" property="uid"></id>
        <result column="uname" property="uname"></result>
        <result column="uphone" property="uphone"></result>
        <result column="upwd" property="upwd"></result>
        <result column="create_time" property="createTime"></result>
    </association>
</resultMap>

扩展资料:简述数据库设计中一对多和多对多的应用场景

动态sql

  • 在映射文件中进行sql语句拼接。
  • where: 中间有内容,自动生成where关键字,自动删掉紧跟其后的and或or。
  • if:条件判断,有test属性写条件表达式,and或or拼接多条件
<select id="selectGoods" parameterType="goods" resultMap="aa">
    select * from goods
    <where>
        <if test="gid!=null">
            and gid=#{gid}
        </if>
        <if test="gname!=null and gname!=''">
            and gname like "%"#{gname}"%"
        </if>
        <if test="gprice!=null and gprice > 0">
            and gprice>=#{gprice}
        </if>
    </where>
</select>
  • set:生成set关键字,用在update标签中(实现字段的部分更新),自动删除最后的逗号.
<update id="updateGoods" parameterType="goods">
  update goods
   <set>
       <if test="gname!=null">
          gname=#{gname},
       </if>
       <if test="gprice!=null">
           gprice=#{gprice},
       </if>
       <if test="gcolor!=null">
           goodsColor=#{gcolor}
       </if>
   </set>
   where gid=#{gid}
</update>
  • foreach:做批量删除与批量添加.批量添加注意按量提交。20条提交一次.
<!--mybatis把所有参数都是封成map,数组的key:array,集合key:list-->
<delete id="delGoodsByKeyArray">
    delete from goods where gid in
    <foreach collection="array" open="(" close=")" item="goodsid" separator=",">
      #{goodsid}
    </foreach>
</delete>

<delete id="delGoodsByKeyList">
    delete from goods where gid in
    <foreach collection="list" open="(" close=")" item="goodsid" separator=",">
        #{goodsid}
    </foreach>
</delete>

<insert id="insertGoodsArray">
    insert into goods(gid,gname,gprice) value
    <foreach collection="array" item="g" separator=",">
        (#{g.gid},#{g.gname},#{g.gprice})
    </foreach>
</insert>

mybatis的三种执行器

  1. SimpleExecutor:每执行一次update或select,就开启一个Statement对象,用完立刻关闭Statement对象。

  2. ReuseExecutor:执行update或select,以sql作为key查找Statement对象,存在就使用,不存在就创建,用完后,不关闭Statement对象,而是放置于Map内,供下一次使用。简言之,就是重复使用Statement对象。

  3. BatchExecutor:执行update(没有select,JDBC批处理不支持select),将所有sql都添加到批处理中(addBatch()),等待统一执行(executeBatch()),它缓存了多个Statement对象,每个Statement对象都是addBatch()完毕后,等待逐一执行executeBatch()批处理。与JDBC批处理相同。

Mybatis 的三种执行器

cache与cache-ref缓存

在这里插入图片描述

  • 所有的缓存都是基于内存,提高查询效率。
  • 标准套路:发起查询–>先去内存查,如果查到则返回–>如果查不到,则查询数据库,并把查询结果放缓存–>返回。
  • 使用缓存会导致的问题:数据同步、数据延迟、数据安全…
  • session级别:默认生效。没有用
    • 只能够在同一个会话中生效。
  • sessionFactory级别:全局唯一对象。
    • 不同会话之间共享缓存。
<!-- 启用二级缓存 -->
<setting name="cacheEnabled" value="true"/>

lazyLoading延迟加载

  • 让用户的体验度更加优秀。
    • 分页、前端图片的延迟加载,树形组件,移动端的信息延迟加载。
    • mybatis中的延迟加载只针对于使用了二次查询。对于第二次查询可延迟查询。
    • 仅支持association关联对象和collection关联集合对象的延迟加载,association指的就是一对一,collection指的就是一对多查询。
    • 它的原理是,使用CGLIB创建目标对象的代理对象,当调用目标方法时,进入拦截器方法,比如调用a.getB().getName(),拦截器invoke()方法发现a.getB()是null值,那么就会单独发送事先保存好的查询关联B对象的sql,把B查询上来,然后调用a.setB(b),于是a的对象b属性就有值了,接着完成a.getB().getName()方法的调用。这就是延迟加载的基本原理。
      当然了,不光是Mybatis,几乎所有的包括Hibernate,支持延迟加载的原理都是一样的。
<!-- 启用延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 积极加载改为消极加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 调用toString,equals不触发延迟对象的加载 -->
<setting name="lazyLoadTriggerMethods" value=""/>

proxy getMapper

  • 代理模式:适合于用在已经存在一个对象,而这个对象中的某些方法需要更新,没有办法改动源码(jar中),需要用代理模式。

  • SqlSeccion.getMapper的动态代理实现

public class TestGetMapper {
    public static void main(String[] args) {
        SqlSessionFactory factory = SessionFactoryUtil.get();
        SqlSession session = factory.openSession();

        SysuserMapper mapper = getMapper(SysuserMapper.class,session);
        Sysuser sysuser = mapper.selectUserByKey(1);
        System.out.println(sysuser);
    }

    public static <T> T getMapper(Class<T> clz,SqlSession session){
        T t = (T)Proxy.newProxyInstance(clz.getClassLoader(), new Class[]{clz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                Class<?> declaringClass = method.getDeclaringClass();
                String name = declaringClass.getName();
                String id = name+"."+methodName;
                MappedStatement mappedStatement = session.getConfiguration().getMappedStatement(id);
                SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
                if(sqlCommandType==SqlCommandType.SELECT){
                    Class<?> returnType = method.getReturnType();
                    if(Collection.class.isAssignableFrom(returnType)){
                        return session.selectList(id,args[0]);
                    }else{
                        return session.selectOne(id,args[0]);
                    }
                }
                return null;
            }
        });

        return t;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值