day02-mybatis笔记

day02-mybatis笔记

今日内容

连接池与事务(了解)

mybatis的动态sql语句(掌握)

mybatis的多表级联查询操作(掌握)

一、连接池与事务(了解)

连接池

连接池:承载连接对象的一个池子,也称之为一个容器,

使用连接池好处,每次使用的连接对象不是重新创建的,而是从池子中拿取的,效率比较高

多个线程不可以拿同一个连接对象,当连接对象.close时候,归还连接对象给连接池

了解内容:

​ 不使用连接池,使用连接对象的时候每次都是要重新创建连接对象

​ 使用连接池,每次使用连接对象的时候都会从空闲池中获取连接对象使用,如果说空闲池中没有了空闲的连接对象,那么mybatis就会自动去活动池中拿取最老的一个连接对象

注意:在实际开发中都会使用连接池操作,type=“POOLED”

关于使用连接池中的空闲池和活动池的说明:

​ 1.在连接池创建的时候默认生成两个池子,空闲和活动池z

​ 2.当连接对象创建的时候会在空闲池中展现,当使用的时候该连接对象就会出现在活动池中

​ 3.当活空闲池中连接数量已经超出了最大数,那么这个时候就会去活动池中找到一个最老的对象,让这个对象恢复初始化,然后去使用

事务

​ 回顾:

​ 事务的特性:原子性,一致性,持久性,隔离性

​ 由于隔离级别造成一些问题:脏读,幻读,不可重复读

​ 事务使用的场景:当我们去改变了数据库表结构的时候才会触发使用事务

​ 事务:提交commit和回滚rollback .保存点(savePoint)

二、mybatis单表的动态sql语句(掌握)

需求:

​ 新增user表

​ 原生态的sql:

insert into user(username,address,sex,birthday)values(#{userName},#{userAddress},#{userSex},#{userBirthday});

​ 这个sql语句有一个弊端:如果username为null,address也为null,执行的sql语句变成:

​ insert into user(username,address,sex,birthday)values(null,null,?,?);这样写不太经济

改变这种状态:

​ 如果username为null,address也为null,执行的sql语句变成:

​ insert into user(sex,birthday) values(?,?)

动态sql语句:

​ 根据不同的条件展现出不同的sql语句,这个就称之为动态sql语句

​ 不管条件是什么样的那么我们的sql语句都是一成不变的,这样称之为静态sql语句

常用的动态sql语句标签

​ if,where,foreach ,trim,set

if标签
     <!--
            条件查询
            if标签表示判断 test属性表示条件
            如果条件成立,则执行if标签里的sql语句,否则,不执行
            如果参数类型是实体类类型的话,sql语句中参数必须和实体类中的属性名称一致
                                        if标签里的条件里的参数也必须和实体类中的属性名称一致
            -->
        <select id="findByMh" parameterType="user" resultType="user">
            select * from user where 1=1
            <if test="username!=null">
              AND  username like #{username}
            </if>
            <if test="id==41">
              AND id=#{id}
            </if>
        </select>
where标签
foreach标签之参数类型是QueryVo包装对象

创建QueryVo包装对象

public class QueryVo {

    private List<User> uList;

dao接口

//批量查询,参数类型是包装对象
    public  List<User> findByPLquery(QueryVo queryVo);

IUserDao.xml

 <!--
        foreach标签表示批量标签,可以应用于批量查询,也可以应用于批量删除
        collection表示集合属性,属性值
                        如果说参数类型是包装类型的话,那么属性等于该包装类型的类里List类型的属性名称
         open表示以什么开始  (
         separator表示括号里的元素之间的连接符 ,
         close表示以什么结束 )
         item属性表示遍历的下标元素,属性值可以随便起
         index表示角标(下标)
         展示数据:在foreach标签之内,#{参数}该参数一定要和item属性的属性值一致
         select * from user where id in(1,2,3,4)
    -->
    <select id="findByPLquery" parameterType="queryVo" resultType="user">
        select * from user where id in
        <foreach collection="uList" open="(" separator="," close=")" item="id" index="a">
            #{id}
        </foreach>

    </select>

测试类

    @Test
    public void test23(){
       QueryVo vo=new QueryVo();
       List list=new ArrayList();
       list.add(41);
        list.add(42);
        list.add(49);
        vo.setuList(list);
        List<User> users = userDao.findByPLquery(vo);
        for (User user2 : users) {
            System.out.println(user2);
        }
    }

问题:

​ 如果把list类型直接作为dao接口方法的参数使用的话,会有什么效果?

foreach标签之参数类型是List类型

dao接口

//批量查询,参数类型是List集合类型
    public  List<User> findByList(List alist);

IUserDao.xml

   <!--参数类型是List集合类型
        如果当前接口参数类型是List类型的话,那么collection属性值必须等于"list"
    -->
    <select id="findByList" parameterType="list" resultType="user">
        select * from user where id in
        <foreach collection="list" open="(" separator="," close=")" item="id" index="a">
            #{id}
        </foreach>

    </select>

做批量操作的时候如果是List类型,那么collection属性值必须是"list";

[外链图片转存失败(img-az75khQk-1562047986778)(assets/1559195670749.png)]

问题:

​ 如果把数组类型直接作为dao接口方法的参数使用的话,会有什么效果?

foreach标签之参数类型是数组类型

dao接口

 //批量删除,参数类型是数组类型  delete from user where id in()
    public  void pdel(int[] ids);

IUserDao.xml

   <!--
            参数类型是数组类型
                如果参数类型是数组类型,那么collection属性值必须等于"array"
        -->
    <delete id="pdel" parameterType="int[]">
          delete from user
        <where>
            <foreach collection="array" open="id in(" separator="," close=")" item="id" index="a">
                #{id}
            </foreach>
        </where>
    </delete>

拓展:

选择性新增操作(trim+if)

dao接口

  //选择性新增
    public  void insertBySelect(User user);

IUserDao.xml

<!--选择性新增
        trim标签表示关联去除指定的字符
        prefix表示前缀,
        suffix表示后缀
        prefixOverrides表示前缀字符 在字段前面的字符
        suffixOverrides表示后缀字符 在字段后面的字符
    -->
    <insert id="insertBySelect" parameterType="user">
        insert into user (
        <trim suffixOverrides=",">
          <if test="username!=null">
              username,
          </if>
            <if test="address!=null">
                address,
            </if>
            <if test="sex!=null">
                sex,
            </if>
            <if test="birthday!=null">
                birthday,
            </if>
        </trim>
        )

        values(
        <trim suffixOverrides=",">
            <if test="username!=null">
                #{username},
            </if>
            <if test="address!=null">
                #{address},
            </if>
            <if test="sex!=null">
                #{sex},
            </if>
            <if test="birthday!=null">
                #{birthday}
            </if>
        </trim>
        )
    </insert>
选择性修改

dao接口


    //选择性修改
    public  void updateBySelect(User user);s

IUserDao.xml

<!--选择性修改
        set标签专门应用于修改操作,智能的去判断最后一个字段,之后的逗号连接符会自动去掉
    -->
    <update id="updateBySelect" parameterType="user">
        update user
        <set>
            <if test="username!=null"> username=#{username},</if>
            <if test="address!=null">address= #{address},</if>
            <if test="sex!=null">sex=#{sex},</if>
            <if test="birthday!=null"> birthday= #{birthday},</if>
        </set>
        <where>
            id=#{id}
        </where>
    </update>

三、多表级联操作

​ 多表:多张表操作

表与表之间的关联关系:

​ 主表和从表是相对而言的,主无从有(主表中没有外键,从表有外键)

​ 分为一对一(一对多),多对一,多对多操作

一对一操作

用户表和账户表,根据账户查询,包含了用户信息[外链图片转存失败(img-zYgcQckx-1562047986779)(assets/1559201951964.png)]

第一步,创建表结构

CREATE TABLE `account` (
  `ID` int(11) NOT NULL COMMENT '编号',
  `UID` int(11) default NULL COMMENT '用户编号',
  `MONEY` double default NULL COMMENT '金额',
  PRIMARY KEY  (`ID`),
  KEY `FK_Reference_8` (`UID`),
  CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `account`(`ID`,`UID`,`MONEY`) values (1,41,1000),(2,45,1000),(3,41,2000);

第二步,要在账户的实体类中加入用户实体类作为属性,目的是为了在java中进行关联两表的关系

public class Account implements Serializable{

    private Integer id;
    private Integer uid;
    private Double money;
    private User user;//关联体现多对一或者一对一的级联关系

第三步,编写dao接口

/*
    * 查询账户,包含用户信息*/
    public List<Account> findAll();

第四步,编写IAccountDao.xml

注意:由于当前两张表的主键都叫id,如果不去处理的话打印出来的account里id为null

解决办法:

在查询账户的时候要取别名把,a表中的id取别名为aid

在resultMap标签中account表的id 的column属性值就不能等于id,必须等于别名aid

注意:如果说操作一对一的时候,是由一的一方去操作另外的一方,那么要在一的一方的实体类映射文件中去加入association标签去关联映射另外一方的实体类

<!--查询账户,包含用户信息-->
    <select id="findAll"  resultMap="accountMap">
        SELECT
        u.*,a.id as aid,uid,money
        FROM USER u,account a WHERE u.id=a.uid
    </select>
    
   <!--
        id表示标签名称,不可重复,type表示当前结果集的类型
    -->
    <resultMap id="accountMap" type="account">
        <id column="aid" property="id"></id>
        <result column="uid" property="uid"></result>
        <result column="money" property="money"></result>
        <!--一对一或者多对一的配置
            property属性值等于当前实体类中关联的另外一方的实体类属性名称
            column表示当前数据库表中的外键
            javaType表示当前另外一方实体类属性的类型

            association专门用来级联一对一和多对一的配置标签,可以理解我专门应用于一的一方的实体类

        -->
        <association property="user" column="uid" javaType="user">
            <id column="id" property="id"></id>
            <result column="username" property="username"></result>
            <result column="birthday" property="birthday"></result>
            <result column="sex" property="sex"></result>
            <result column="address" property="address"></result>
        </association>
    </resultMap>
    

第五步,测试

   //测试一对一,由account查询user
    @Test
    public  void demo1(){
       /* Account account = accountDao.findById(1);
        System.out.println(account);*/
        List<Account> accounts = accountDao.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

一对多操作

​ 由用户信息查询,包含了账户信息 称之为一对多操作

内连接:

​ 主要查询的是两张表中有关联的数据信息,没有关联的不显示

左连接:

​ 主要查询的是两张表,以左表为主,(左表中的所有数据信息全部查询出来,不管有没有关联),以右表为辅(右表中的有关联左表的数据信息展示出来,那么没有关联不显示)

sql:

​ SELECT
u.*,a.id as aid,uid,money
FROM USER u left join account a on u.id=a.uid

第一步,编写User实体类,目的是要在该实体类中关联账户信息,要在当前实体类中加入一个List集合,用来承载多个账户信息的实体类

public class User implements Serializable{

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    private List<Account> accountList;//在一的一方实体类中加入一个集合,用来承载多的一方的实体类

第二步,编写IUserDao

  //查询用户,包含角色
    public List<User> findUserAll();

第三步,编写IUserDao.xml

如果说在一对多的时候,由一的一方去操作多的一方,在一的一方的实体类映射文件中要取使用collection标签去级联多的一方的实体类

   <select id="findUserAll" resultMap="userMap">
         SELECT
        u.*,a.id as aid,uid,money
        FROM USER u left join account a on u.id=a.uid

    </select>
    
    
    <resultMap id="userMap" type="user">
        <id column="id" property="id"></id>
        <result column="username" property="username"></result>
        <result column="birthday" property="birthday"></result>
        <result column="sex" property="sex"></result>
        <result column="address" property="address"></result>
        <!--一对多级联配置
            property表示当前实体类user中的list集合的属性名称
            column建议使用外键
            ofType表示当前list集合中泛型的类型
            collection标签表示集合,专门用来级联多的一方的配置
        -->
        <collection property="accountList" column="uid" ofType="account">
            <id column="aid" property="id"></id>
            <result column="uid" property="uid"></result>
            <result column="money" property="money"></result>
        </collection>
    </resultMap>

第四步,测试

 //测试多对一,由user查询account
    @Test
    public  void demo1(){
        List<User> users = userDao.findUserAll();
        for (User user : users) {
            System.out.println(user);
        }
    }

多对多操作

应用场景:一般情况下我们在做权限控制的时候使用多对多操作。

注意:我们在做多对多关系的时候必须有中间表存在

[外链图片转存失败(img-8zV18Lww-1562047986780)(assets/1559213231722.png)]

由查询角色,包含用户信息

sql:

SELECT u.*,r.id AS rid,role_name,role_desc FROM role r 
	LEFT JOIN user_role ur ON r.`ID`=ur.`RID`
	LEFT JOIN USER u ON u.`id`=ur.`UID`

第一步,修改角色实体类,在当前实体类中加入一个List集合,用来承载多个用户的实体类

public class Role {
    private Integer id;
    private String roleName;
    private String roleDesc;
    
    private List<User> uList;//关联用户实体类级联

第二步,编写IRoleDao接口

public interface IRoleDao {

    public List<Role> findRoleAll();
}

第三步,编写IRoleDao.xml

<mapper namespace="com.itheima.dao.IRoleDao">
    <resultMap id="roleMap" type="role">
            <id column="rid" property="id"></id>
            <result column="role_name" property="roleName"></result>
            <result column="role_desc" property="roleDesc"></result>
        <!--关联用户-->
        <collection property="uList" column="rid" ofType="user">
            <id column="id" property="id"></id>
            <result column="username" property="username"></result>
            <result column="birthday" property="birthday"></result>
            <result column="sex" property="sex"></result>
            <result column="address" property="address"></result>
        </collection>
    </resultMap>
    <select id="findRoleAll" resultMap="roleMap" >
      SELECT u.*,r.id AS rid,role_name,role_desc FROM role r
        LEFT JOIN user_role ur ON r.`ID`=ur.`RID`
        LEFT JOIN USER u ON u.`id`=ur.`UID`
    </select>
</mapper>

第四步,测试

//由查询角色,包含用户信息
    @Test
    public void demo1(){
        List<Role> roles = roleDao.findRoleAll();
        for (Role role : roles) {
            System.out.println(role);
        }
    }
由查询用户,包含角色信息(作业)

sql:

SELECT * FROM USER u
	LEFT JOIN user_role ur ON u.`ID`=ur.`UID`
	LEFT JOIN role r ON r.`ID`=ur.`RID`

第一步,修改用户实体类,在当前实体类中加入一个List集合,用来承载多个角色的实体类

第二步,第二步,编写IUserDao接口

第三步,编写IUserDao.xml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值