Mybatis基础

mybatis配置文件详解(mybatis.cfg.xml)

environments

environment

  1. DataSource

    pooled-->连接池

  2. TransactionManager

    JDBC-->以JDBC的方式对数据库提交与回滚事务

properties

property

属性优先级问题

typeAliases

别名(不建议使用)

<typeAliases>
    <typeAlias alias="User" type="org.apache.ibatis.submitted.complex_property.User"/>
  </typeAliases>

typeHandlers

一般情况下我们不需要额外添加

settings

默认配置都是友好的

mappers

mapper的数量与javabean一致

<mappers>
    <mapper resource="com.sz.mapper/GirlMapper.xml"/>
  </mappers>
  //下面是指定Mapper接口的包
  <mappers>
    <package name="com.mapper"/>
  </mappers>

mybatis参数问题

<?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="com.sz.mapper.GirlMapper">//namespace属性必须是注册的Mapper。
<insert id="insert">
    insert into girl(name,flower,birthday) values(#{name},#{flower},#{birthday})
</insert>
<select id="queryById" resultType="com.sz.pojo.Girl">
    select * from girl where id=#{id}
</select>
</mapper>

mapper拥有4种子标签select insert update delete ,insert update delete只需要指定id属性,select只需要指定id,resultType属性,对于parameterType,这是入参类型,绝大部分情况下能够自我推断

传参问题

单个基本数据类型与String

如果仅仅是简单的一个单值传入,那么#{}表达式里面随便写什么都可以,只有一个参数,mybatis没有入参绑定的烦恼

多个基本数据类型或String入参问题

  1. 默认xml中的#{}里面放param1,param2或者arg0,arg1默认配置很不友好,不推荐使用

  2. 注解模式

    GirlMapper中:
    Girl queryByNameFlower(@Param("name") String name,@Param("flower") String flower);
    GirlMapper.xml中:
    <select id="queryByNameFlower" resultType="com.sz.pojo.Girl">
     select * from girl where name=#{name} and flower=#{flower}
    </select>
    

单个Javabean

默认通过javabean里面的属性的名称去引用,通过get方法去找这个值

MAP

GrilMapper中:
Girl queryByNameFlowerMap(Map<String,Object> map);
GrilMapper.xml中:
<select id="queryByNameFlowerMap" resultType="com.sz.pojo.Girl">
        select * from girl where name=#{username} and flower=#{loveflower}
</select>
Test01中:
SqlSession sqlSession= MybatisUtil.getSession();
        GirlMapper mapper=sqlSession.getMapper(GirlMapper.class);
        Map<String,Object> map=new HashMap<>();
        map.put("username","如花");
        map.put("loveflower","hhhh");
        Girl g=mapper.queryByNameFlowerMap(map);
        System.out.println(g.getBirthday());
        sqlSession.commit();
        sqlSession.close();

动态SQL

OGNL

  • if
  • choose (when, otherwise)choose里面的when,自动匹配第一个满足的when
  • trim (where, set)
  • foreach
    bind标签(解决模糊查询)
<select id="queryByName" resultType="com.sz.pojo.Girl">
        <bind name="bin" value="'%'+name+'%'"></bind>
        select * from girl
        <where>
            name like #{bin}
        </where>
  </select>

sql标签(减少重复代码)

<sql id="baseColumn">
       name,flower,birthday
    </sql>
    <select id="queryAll" resultType="com.sz.pojo.Girl">
        select
        <include refid="baseColumn"></include>
        from girl
    </select>

Mybatis配置log4j

  1. 添加依赖
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  1. 在resources里面新建一个log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...,com.sz.mapper是GirlMapper的包名
log4j.logger.com.sz.mapper=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

缓存

一级缓存(存储作用域为 Session):

MyBatis中一级缓存是默认开启的,即在查询中(一次SqlSession中)。只要当SqlSession不关闭,那么你的操作会默认存储使用一级缓存。

二级缓存(存储作用域为 Mapper(Namespace)):

mybatis.cfg.xml中:
<!--开启二级缓存-->
<settings>
    <setting name="cacheEnabled" value="true"/>
</settings>
GirlMapper.xml中:
<mapper namespace="com.sz.mapper.GirlMapper">
<cache/>
</mapper>

如果开启了二级缓存,先去二级缓存中尝试命中,如果也无法命中,尝试去一级缓存中尝试命中,还不命中,再去数据库里面查询

二级缓存例子

SqlSession sqlSession= MybatisUtil.getSession();
        SqlSession sqlSession2= MybatisUtil.getSession();
        GirlMapper mapper=sqlSession.getMapper(
                GirlMapper.class
        );
        GirlMapper mapper2=sqlSession2.getMapper(
                GirlMapper.class
        );
        //使用二级缓存时,Girl类必须实现一个Serializable接口===> Girl implements Serializable
        List<Girl> list = mapper.queryByName("花");
        for (Girl g: list) {System.out.println(g.getName());}
        sqlSession.commit();
        /*一定要提交事务之后二级缓存才会起作用
        因为,二级缓存是从cache(mapper.xml中定义的cache)中取得
        如果session不commit,那么,数据就不会放入cache中*/
        mapper2.queryByName("花");
        //由于使用的是两个不同的SqlSession对象,所以即使查询条件相同,一级缓存也不会开启使用
        sqlSession2.commit();
        sqlSession.close();
        sqlSession2.close();

放入二级缓存区的对象必须序列化

缓存失效方式:

  1. 如果查询之后进行增删改的行为,将导致缓存失效
  2. 强制清空缓存,SqlSession.clearCache();

对应关系

一对一

比如girl表对于girldetail表

<resultMap id="SelectMap" type="com.sz.pojo.GirlDetail">
<id column="id" jdbcType="BIGINT" property="id"></id>
        <result column="gid" jdbcType="BIGINT" property="gid"></result>
        <result column="phone" jdbcType="VARCHAR" property="phone" ></result>
        <result column="address" jdbcType="VARCHAR" property="address" ></result>
        <association property="girl" javaType="com.sz.pojo.Girl">
            <id column="id" jdbcType="BIGINT" property="id"></id>
            <result column="name" jdbcType="VARCHAR" property="name"></result>
            <result column="flower" jdbcType="VARCHAR" property="flower" ></result>
            <result column="birthday" jdbcType="DATE" property="birthday" ></result>
        </association>
    </resultMap>
    <select id="queryByIdAndGid" resultMap="SelectMap">
       select * from girldetail as b ,girl as a where a.id=#{id} and b.gid =#{id}
    </select>

有个问题就是girl与girldetail表具有同名字段id,那么查询的id是哪个的呢?

在sql中,哪个表名在前面就是哪个表的id值,这里是girldetail在前面

解决方案

<resultMap id="SelectMap" type="com.sz.pojo.GirlDetail">
<id column="gd" jdbcType="BIGINT" property="id"></id>
        <result column="gid" jdbcType="BIGINT" property="gid"></result>
        <result column="phone" jdbcType="VARCHAR" property="phone" ></result>
        <result column="address" jdbcType="VARCHAR" property="address" ></result>
        <association property="girl" javaType="com.sz.pojo.Girl">
            <id column="g" jdbcType="BIGINT" property="id"></id>
            <result column="name" jdbcType="VARCHAR" property="name"></result>
            <result column="flower" jdbcType="VARCHAR" property="flower" ></result>
            <result column="birthday" jdbcType="DATE" property="birthday" ></result>
        </association>
    </resultMap>
    <select id="queryByIdAndGid" resultMap="SelectMap">
    SELECT b.id AS gd,a.id AS g FROM girldetail AS b ,girl AS a WHERE a.id=#{id} and b.gid =#{id}
    </select>

注意resultMap可以继承

分步查询

一对多

<resultMap id="BaseMap" type="com.sz.pojo.Girl">
        <id column="id" jdbcType="BIGINT" property="id"></id>
        <result column="name" jdbcType="VARCHAR" property="name"></result>
        <result column="flower" jdbcType="VARCHAR" property="flower" ></result>
        <result column="birthday" jdbcType="DATE" property="birthday" ></result>
    </resultMap>
    <resultMap id="AllMap" extends="BaseMap" type="com.sz.pojo.All">
        <collection property="blogList" ofType="com.sz.pojo.Blog">
            <result column="title" jdbcType="VARCHAR" property="title"></result>
            <result column="summary" jdbcType="VARCHAR" property="summary" ></result>
            <result column="content" jdbcType="VARCHAR" property="content" ></result>
            <collection property="commentList" ofType="com.sz.pojo.Comment">
                <result column="contents" jdbcType="VARCHAR" property="contents" ></result>
            </collection>
        </collection>
    </resultMap>
    <select id="queryAllData" resultMap="AllMap">
        SELECT * FROM girl AS t1,blog AS t2,COMMENT AS t3 WHERE t1.id=t2.u_id AND t2.id=t3.b_id;
    </select>

javabean的设计:

public class All extends Girl{
private List<Blog> blogList;
}
public class Blog {
    private int id;
    private String title;
    private String summary;
    private String content;
    private int u_id;
private List<Comment> commentList;
}
public class Comment {
    private int id;
    private String contents;
    private int b_id;
}

数据库表设计与javabean设计

不管是一对一还是一对多的关系,外键约束都是在子表里面添加,想删除主表一条数据时,必须要把子表里对应的约束数据先删掉

如果是一对一:在子表的javabean中加一个父表的javabean的对象作为属性

如果是一对多:在父表的javabean中加一个集合,里面放子表对应的javabean的对象作为属性

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,331评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,372评论 3 398
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,755评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,528评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,526评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,166评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,768评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,664评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,205评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,290评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,435评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,126评论 5 349
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,804评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,276评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,393评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,818评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,442评论 2 359

推荐阅读更多精彩内容

  • 使用原生jdbc的问题 数据库连接, 使用时就创建,不使用就立即释放,对数据库进行频繁地链接开启和关闭,造成数据库...
    wtmxx阅读 728评论 1 3
  • 3.XML映射文件 MyBatis 的真正强大在于它的映射语句,也是它的魔力所在。由于它的异常强大,映射器的 XM...
    王侦阅读 316评论 0 0
  • MyBatis 是什么? MyBatis是第一个支持自定义SQL、存储过程和高级映射的类持久框架。 MyBatis...
    Java_苏先生阅读 380评论 0 0
  • 基础知识 安装 对原生态jdbc程序中问题总结 环境 java环境:jdk jdbc程序 使用jdbc查询mysq...
    全满阅读 620评论 0 1
  • 一直练字,却不懂笔画里的真谛。 写得一笔潇洒的字,却未必活得潇洒。 很小的时候,就开始练字,一笔一划,中规中矩的正...
    浅笑安然焉阅读 609评论 0 4