Mybatis入门【三】

Mybatis

一、内容介绍

  1. 框架的介绍

  2. 介绍mybatis框架

  3. JDBC于Mybatis框架的比较

  4. 自定义Mybatis框架

  5. mybatis框架的快速入门

二、框架的介绍

1、什么是框架
1. 半成品,
2. 饭店:买菜,油盐酱醋-- 洗菜 -- 炒菜--做饭 -- 刷锅,洗碗
2、框架能解决什么问题
1、把技术封装起来
2、在开发中不应该考虑技术, 专注于逻辑(业务)开发
3, 框架时位于底层技术 和应用程序之间的代码
3、三层架构中常用的框架
a、web:表现层: 处理用户请求和响应
		servlet -- struts(放弃) -- struts2(放弃) -- springMVC(主流)
b、service:业务层
		自己写业务 --- ejb -- spring(整合框架,业务)(不可取代)
c、dao: 持久层(数据接收对象)
		jdbc--dbutils--BeanUtils -- jdbcTemplate -- hibernate(放弃)--mybatis(主流)--spring data jpa(趋势)
		
		主流:整合: springmvc + spring + mybatis = ssm
		趋势:整合:springmvc + spring +spring data  = spring全家桶

三、mybatis框架的介绍

了解Mybatis

MyBatis是一款优秀的持久层框架,它可以与Java程序无缝集成,提供了一种简单而灵活的方式来访问数据库。本文将介绍MyBatis的基本概念、使用方法和一些最佳实践。

一、MyBatis基本概念

  1. Mapper:MyBatis中的映射器(Mapper)是接口,用于定义SQL语句的映射关系。它通常包含一组方法,每个方法对应一个SQL语句,这些方法的参数类型应该与SQL语句中的参数类型相对应。
  2. XML文件:MyBatis使用XML文件作为配置文件,其中包含了所有的映射器接口和SQL语句。在XML文件中,可以使用标签定义SQL语句的格式、参数类型、返回值类型等信息。
  3. SqlSessionFactory:SqlSessionFactory是MyBatis的核心组件之一,它负责创建SqlSession对象,并提供给应用程序使用。SqlSessionFactory可以通过读取XML文件或者注解来创建SqlSession对象。

二、MyBatis使用方法

  1. 配置MyBatis环境:在使用MyBatis之前,需要先配置MyBatis的环境。这包括设置数据源、注册映射器接口和加载XML文件等操作。
  2. 编写映射器接口:根据业务需求,编写相应的映射器接口,并在其中定义SQL语句。
  3. 编写XML文件:在XML文件中定义SQL语句的格式、参数类型、返回值类型等信息。
  4. 注册映射器接口:将编写好的映射器接口注册到SqlSessionFactory中。
  5. 获取SqlSession对象:通过SqlSessionFactory获取SqlSession对象,然后使用该对象执行SQL语句。

三、MyBatis最佳实践

  1. 避免硬编码:尽量避免在代码中直接写SQL语句,而是使用映射器接口来定义SQL语句。这样可以提高代码的可维护性和可扩展性。
  2. 使用动态SQL:如果需要根据不同的条件来执行不同的SQL语句,可以使用动态SQL来实现。动态SQL可以根据条件生成不同的SQL语句,从而提高了代码的灵活性和可重用性。
  3. 缓存机制:为了提高查询效率,可以使用缓存机制来缓存查询结果。MyBatis提供了一级缓存和二级缓存两种缓存机制,可以根据实际情况选择合适的缓存机制。

总之,MyBatis是一款非常优秀的持久层框架,它可以帮助开发人员轻松地访问数据库,并提供了灵活的配置方式和丰富的功能支持。通过掌握MyBatis的基本概念、使用方法和最佳实践,可以更好地利用MyBatis来开发高质量的Java应用程序。

1、jdbc中的代码
package com.itheima;

import com.itheima.domain.User;
import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 回顾jdbc代码
 */
public class TestJDBC {

    @Test
    public void test(){

        List<User> userList = new ArrayList<>();

        //1. 注册驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String url = "jdbc:mysql://localhost:3306/mybatisdb_331";
        String username = "root";
        String password = "root";
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            //2. 获取连接
            conn = DriverManager.getConnection(url, username ,password);
            // 3. SQL语句
            String sql = "select * from user";
            //4. 创建statement对象: Statement , PreparedStatement
            pst = conn.prepareStatement(sql);
            //5. 执行SQL语句,返回结果集
            rs = pst.executeQuery();
            //6. 处理结果集
            while(rs.next()){//判断是否有下一条记录,如果有,说明有一个User对象
                User user = new User();
                //获取ResultSet中的值,赋值给user对象
                int id = rs.getInt("id");
                user.setId(id);
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setSex(rs.getString("sex"));
                user.setAddress(rs.getString("address"));
                //添加到集合中
                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //7. 释放资源: 先开后关
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(pst != null){
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

        //打印结果
        for (User user : userList) {
            System.out.println(user);
        }

    }
}

2、jdbc代码中的问题
a、频繁创建和释放数据库的连接对象,造成资源的浪费. 使用数据库连接池可以解决(c3p0 ,dbcp, spring jdbc ,durid)
b、sql语句硬编码(写死),如果数据库发生改变,需要重新编译代码,再运行 。 可以考虑把sql语句写到配置文件中
c、传参数硬编码,必须按照特定的顺序传参
d、处理结果集硬编码,如果改变了数据库,结果集的映射必须重新写,需要重新编译代码,再运行
e、连接的配置信息硬编码
3、mybatis框架的概述

四、Mybatis框架的快速入门

1、添加依赖(jar)
 <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
2、编写pojo对象
package com.itheima.domain;

/**
 * 包装类型: 初始值为null
 * 基本数据类型:本身的值就是一个状态
 *
 */
public class User {
    private Integer id;
    private String username;
    private String password;
    private String sex;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

3、编写映射文件
<?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.itheima.dao.UserDao">
    <select id="findAll" resultType="com.itheima.domain.User">
        select * from user
    </select>
</mapper>
4、编写核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatisdb_331?characterEncoding=utf8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <!--关联映射文件-->
	<mappers>
		<mapper resource="com/itheima/mapper/UserMapper.xml"></mapper>
    </mappers>
</configuration>    
5、测试框架
package com.itheima;


import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class TestCustomFrame {

    @Test
    public void test(){
        //获取配置文件的输入流对象
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //创建SqlSessionFactory对象
        SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        //获取sqlSession对象
        SqlSession sqlSession = sessionFactory.openSession();
        //执行sql语句
        List list = sqlSession.selectList("com.itheima.dao.UserDao.findAll");
        //遍历结果集
        for (Object o : list) {
            System.out.println(o);
        }
        //关闭资源
        sqlSession.close();
    }
}

五、mybatis实现CRUD
a、mybatis 的中文文档网址:http://www.mybatis.org/mybatis-3/zh/getting-started.html
b、 selectList 查询多个对象,返回一个list集合(也能查询一个)
    selectOne: 查询单个对象,返回一个对象
c、日志记录日常操作
	引入依赖: 
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
  引入日志的配置文件:log4j.properties
 d、增删改查
 	<!--UserMapper删除操作-->
    <delete id="del" parameterType="java.lang.Integer">
        delete from user where id = #{id}
    </delete>
 	<!--测试类-->   
    @Test
    public void testDel(){
        //获取输入流对象
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("SqlMapConfig.xml");
        //获取SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象
        //获取的sqlsession不能自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //执行sql语句
        sqlSession.delete("userMapper.del",3);
        //提交:只要修改了数据库必须提交
        sqlSession.commit();

        sqlSession.close();
    }
 e、模糊查询
 	参数: %a% 
 		配置文件: username like #{username}
 	参数: a
 		配置文件1: username like "%"#{username}"%"
 		配置文件2: username like "%${value}%"
 							如果传的是简单类型必须使用value
 							如果是pojo,属性名引用
 d、参数
 		简单类型: 基本数据类型,String
 				如果${} 必须用value引用
 				如果#{} 随便写
 		pojo类型:属性名引用	
 e、${} 与 #{}区别
 	${}:直接拼接,不会转换类型, 不能防注入
 	#{}:转换类型后拼接, 相当于占位符?,可以防注入

六、核心配置文件详解
1. 配置文件中的标签和顺序
properties?, 						配置属性(学习)
settings?, 							全局配置:缓存,延迟加载
typeAliases?, 					类型别名(学习)
typeHandlers?, 					类型转换(操作)(了解)
objectFactory?, 	 objectWrapperFactory?,  reflectorFactory?, 
plugins?, 							插件:分页插件
environments?, 					环境配置(数据源)
databaseIdProvider?, 		
mappers?								引入映射配置文件(学习)

? : 一个或者零个
| : 任选其一
+ : 最少一个
* : 零个或多个
, : 必须按照此顺序编写

七、输入参数类型和输出参数类型
1. 输入参数
	简单类型: 基本数据类型+ String类型
				#{} :名称随便
				${} :${value}
	pojo 类型
		#{} :${} : 属性名引用
	包装对象类型
		引用  #{属性.属性名}
	Map集合
		引用: #{key}
	多个参数
		引用时:#{param1},#{param2}.....#{paramN}
2. 返回值类型
	如果列与属性名不一致,对应的属性为null, 必须写映射配置
八、mybatis自带数据源
	<!--数据库的环境:
    default; 指定默认的环境
        -->
    <environments default="development">
        <!--id: 环境唯一的标志 -->
        <environment id="development">
            <!--事务管理: jdbc-->
            <transactionManager type="JDBC"/>
            <!--
                dataSource: 数据源(数据库连接池)配置
                type="POOLED" : 数据源的类型配置
                    POOLED :使用mybatis的自带数据源配置
                    UNPOOLED: 不使用数据源配置, 使用Connection操作数据库
                    JNDI:JNDI服务 数据源配置
            -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatisdb_331"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
九、事务问题
package com.itheima;

import com.itheima.domain.User;
import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 回顾jdbc代码
 */
public class TestJDBC {

    @Test
    public void test(){

        List<User> userList = new ArrayList<>();

        //1. 注册驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String url = "jdbc:mysql://localhost:3306/mybatisdb_331";
        String username = "root";
        String password = "root";
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            //2. 获取连接
            conn = DriverManager.getConnection(url, username ,password);
            //事务1 :设置事务手动提交(不能自动提交)
            conn.setAutoCommit(false);
            // 3. SQL语句
            String sql1 = "insert into ......";
            String sql2 = "insert into ......";
            //4. 创建statement对象: Statement , PreparedStatement
            pst = conn.prepareStatement(sql1);
            //5. 执行SQL语句,返回结果集
            pst.executeUpdate();

            pst = conn.prepareStatement(sql2);
            pst.executeUpdate();
            //事务2:提交事务
            conn.commit();
        } catch (SQLException e) {
            //事务3:出现异常,回顾
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            //事务4: 还原状态,设置事务为自动提交
            if(conn != null){
                try {
                    conn.setAutoCommit(true);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            //7. 释放资源: 先开后关
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(pst != null){
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

        //打印结果
        for (User user : userList) {
            System.out.println(user);
        }

    }
}
十、动态sql语句
1、问题
	<!--
        多条件查询
        如果传递参数个数不对,会出现异常,动态sql可以解决
    -->
    <select id="findByCondition" resultMap="users" parameterType="user">
        select * from user where uname like "%"#{username}"%"  and sex = #{sex}
    </select>
2、if语句
<!--
        多条件查询
    -->
    <select id="findByCondition" resultMap="users" parameterType="user">
        select * from user where 1=1
        <if test="username != null">
            and uname like "%"#{username}"%"
        </if>
        <if test="sex != null">
            and sex = #{sex}
        </if>
    </select>
3、where语句
 <!--
        where : 帮助程序员处理第一个and
            多条件 都写上  and关键字
    -->
    <select id="findByCondition" resultMap="users" parameterType="user">
        select * from user
        <where>
            <if test="username != null">
                and uname like "%"#{username}"%"
            </if>
            <if test="sex != null">
                and sex = #{sex}
            </if>
        </where>
    </select>
4、SQL片段
<!--SQL片段
把重复的sql语句提取出来,需要使用时引用即可

id="": 唯一标志
文本:sql语句
-->
    <sql id="select_user">select * from user</sql>

--       关联使用sql片段
--         include :包含
--         refid: 关联的sql片段的id
--         ref :references
        <include refid="select_user"></include>
5、foreach语句
<delete id="delByArray" parameterType="integer[]">
        delete from user where
        <!--
            foreach循环标签
                collection: 参数的类型:如果是集合:list,如果是数组: array
                open :前缀
                close:后缀
                separator: 分隔符
                item:  循环中的每一个对象
                index:循环中的索引( 一般不用)
        -->
        <foreach collection="array" open="uid in (" close=")" separator="," item="id">
            #{id}
        </foreach>
    </delete>

    <delete id="delByList" parameterType="list">
        delete from user where
        <!--
            foreach循环标签
                collection: 参数的类型:如果是集合:list,如果是数组: array
                open :前缀
                close:后缀
                separator: 分隔符
                item:  循环中的每一个对象
                index:循环中的索引( 一般不用)
        -->
        <foreach collection="list" open="uid in (" close=")" separator="," item="id">
            #{id}
        </foreach>
    </delete>
十一、多表关联
1、一对一
a、第一种方法:accountUser extends Account
1)配置文件配置
<resultMap id="accountUsers" type="accountUser">
        <result column="uname" property="username"></result>
    </resultMap>

    <select id="findAllAccountUser" resultMap="accountUsers">
         select * from account a, user u where a.u_id = u.uid
 </select>
 2) pojo配置
 	/**
 * 继承了Account,就拥有Account中所有的属性
 * 单独添加User的属性
 */
public class AccountUser extends  Account {
    private Integer uid;
    private String username;
    private String password;
    private String address;
    private Date birthday;
    private String sex;
}
3) Dao接口
	/**
     * 查询所有的账户:包含对应的用户信息
     * @return
     */
    public List<AccountUser> findAllAccountUser();
b、第二种方法
1)配置文件
	<resultMap id="accounts" type="Account">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="money" property="money"></result>
        <result column="u_id" property="u_id"></result>
        <!--映射user中的属性-->
        <result column="uid" property="user.id"></result>
        <result column="uname" property="user.username"></result>
        <result column="address" property="user.address"></result>
        <result column="birthday" property="user.birthday"></result>
        <result column="sex" property="user.sex"></result>
        <result column="password" property="user.password"></result>
    </resultMap>
  2)pojo 
  public class Account {
    private Integer id;
    private String name;
    private Float money;
    private Integer u_id;
//    一个账户对应一个用户
    private User user;
  }
  3)  Dao接口
  /**
     * 查询所有的账户:包含对应的用户信息
     * @return
     */
    public List<Account> findAllAccount();
c、第三种方法
1)配置文件
	<resultMap id="accounts" type="Account">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="money" property="money"></result>
        <result column="u_id" property="u_id"></result>
        <!--映射user中的属性-->
        <!--association 映射单个对象
        	property:属性名
        	javaType:属性对应的类型
        -->
        <association property="user" javaType="user">
            <id column="uid" property="id"></id>
            <result column="uname" property="username"></result>
            <result column="address" property="address"></result>
            <result column="birthday" property="birthday"></result>
            <result column="password" property="password"></result>
            <result column="sex" property="sex"></result>
        </association>
    </resultMap>
  2)pojo 
  public class Account {
    private Integer id;
    private String name;
    private Float money;
    private Integer u_id;
//    一个账户对应一个用户
    private User user;
  }
  3)  Dao接口
  /**
     * 查询所有的账户:包含对应的用户信息
     * @return
     */
    public List<Account> findAllAccount();
2、一对多
a.  pojo
	public class User {
    private Integer id;
    private String username;
    private String password;
    private String address;
    private Date birthday;
    private String sex;
    //一个用户对应多个账户
    private List<Account> accountList;
  }
b. 配置文件
	    <resultMap id="users" type="User">
        <id column="uid" property="id"></id>
        <result column="uname" property="username"></result>
        <result column="password" property="password"></result>
        <result column="address" property="address"></result>
        <result column="birthday" property="birthday"></result>
        <result column="sex" property="sex"></result>
        <!--Collection : 映射accountList 属性
                property: 对应的属性名
                ofType: 集合中的元素类型: association 中javaType效果一致
        -->
        <collection property="accountList" ofType="account">
            <id column="id" property="id"></id>
            <result column="name" property="name"></result>
            <result column="money" property="money"></result>
            <result column="u_id" property="u_id"></result>
        </collection>
    </resultMap>

    <select id="findAll" resultMap="users">
         select * from user u left join account a on u.uid = a.u_id
    </select>
 c、Dao接口
 /**
     * 返回所有的user对象,包含用户对应账户信息
     * @return
     */
    public List<User> findAll();
3、多对多
a. sql语句
create table role(
	id int primary key auto_increment,
	roleName varchar(20),
	roleDesc varchar(20)
)

create table user_role(
	uid int , 
	rid int , 
	-- 联合主键: 两列以上为主键列, 两列不能同时相同
	primary key(uid,rid),
	foreign key(uid) references user(uid),
	foreign key(rid) references role(id)
)
b. pojo
  public class User {
    private Integer id;
    private String username;
    private String password;
    private String address;
    private Date birthday;
    private String sex;
//    一个用户有多个角色
    private List<Role> roleList;
  }
c、配置文件
<mapper namespace="com.itheima.dao.UserDao">
    <resultMap id="users" type="user">
        <id column="uid" property="id"></id>
        <result column="uname" property="username"></result>
        <result column="address" property="address"></result>
        <result column="birthday" property="birthday"></result>
        <result column="sex" property="sex"></result>
        <result column="password" property="password"></result>
        <!--一个用户对应多个角色: roleList-->
        <collection property="roleList" ofType="role">
            <id column="id" property="id"></id>
            <result column="roleName" property="roleName"></result>
            <result column="roleDesc" property="roleDesc"></result>
        </collection>
    </resultMap>

    <select id="findAll" resultMap="users">
      select u.* ,r.* from user u left join user_role ur on u.uid = ur.uid left join role r on r.id = ur.rid
    </select>
</mapper>
d、dao接口
    /**
     * 返回所有的user对象,包含用户对应的角色对象
     * @return
     */
    public List<User> findAll();

角色到用户的关系

a、pojo
	public class Role {
    private Integer id;
    private String roleName;
    private String roleDesc;
//    一个角色对应多个用户'
    private List<User> userList;
  }
b、配置文件
<mapper namespace="com.itheima.dao.RoleDao">
    <resultMap id="roles" type="role">
        <id column="id" property="id"></id>
        <result column="roleName" property="roleName"></result>
        <result column="roleDesc" property="roleDesc"></result>
        <collection property="userList" ofType="User">
            <id column="uid" property="id"></id>
            <result column="uname" property="username"></result>
            <result column="address" property="address"></result>
            <result column="birthday" property="birthday"></result>
            <result column="sex" property="sex"></result>
            <result column="password" property="password"></result>
        </collection>
    </resultMap>

    <select id="findAll" resultMap="roles">
      select r.*,u.* from role r left join user_role ur on r.id = ur.rid left join user u on u.uid = ur.uid
    </select>
</mapper>
c、dao接口
		/**
     * 查询所有的角色,包含用户对象
     * @return
     */
    public List<Role> findAll();
十二、mybatis延迟加载
a、什么是延迟加载
1. 也叫懒加载
2. 什么时候需要,什么时候去获取
	什么时候需要该数据,什么时候执行sql语句去查询
b、一对一延迟加载
1. pojo
	public class Account {
    private Integer id;
    private String name;
    private Float money;
    private Integer u_id;
    //一个账户对应一个用户对象
    private User user;
  }
2. accountDao.java
	public interface AccountDao {

    /**
     * 查询所有的账户:包含用户信息
     * @return
     */
    public List<Account> findAll();
	}	
3. userDao.java
public interface UserDao {

    /**
     * 根据id查询用户对象
     * @param id
     * @return
     */
    public User findById(Integer id);
}
4. AccountDao.xml
<mapper namespace="com.itheima.dao.AccountDao">
    <resultMap id="accounts" type="account">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="money" property="money"></result>
        <result column="u_id" property="u_id"></result>
        <!--映射user属性:原来的代码-->
        <!--<association property="user" javaType="User">-->
            <!--<id column="uid" property="id"></id>-->
            <!--<result column="uname" property="username"></result>-->
            <!--<result column="address" property="address"></result>-->
            <!--<result column="birthday" property="birthday"></result>-->
            <!--<result column="password" property="password"></result>-->
            <!--<result column="sex" property="sex"></result>-->
        <!--</association>-->
        <!--映射user属性:现在的代码
            column="u_id": 要通过该列去查询用户的对象
            select: 映射到了要执行的方法 :mapperId=namespace.id

            fetchType="lazy"  :加载的方法:lazy 延迟加载,  eager:立即加载
        -->
        <association property="user" javaType="User" column="u_id"
                     select="com.itheima.dao.UserDao.findById" fetchType="lazy"></association>
    </resultMap>
    <select id="findAll" resultMap="accounts">
        select * from account
    </select>
</mapper>
5. UserDao.xml
<mapper namespace="com.itheima.dao.UserDao">
    <resultMap id="users" type="user">
        <id column="uid" property="id"></id>
        <result column="uname" property="username"></result>
    </resultMap>
   <select id="findById" resultMap="users" parameterType="int">
        select * from user where uid = #{id}
   </select>
</mapper>
c、一对多延迟加载
1. User.java
public class User {
    private Integer id;
    private String username;
    private String address;
    private String password;
    private Date birthday;
    private String sex;

    //一个用户对应多个账户
    private List<Account> accountList;
 }
 2. UserDao.java
 	public interface UserDao {

    /**
     * 查询所有的用户:包含账户信息
     * @return
     */
    public List<User> findAll();
}
3. AccountDao.java
public interface AccountDao {

    /**
     * 根据用户名查询对应的账户信息
     * @param userId
     * @return
     */
    public List<Account> findByUserId(Integer userId);
}
4. UserDao.xml
	<mapper namespace="com.itheima.dao.UserDao">

    <resultMap id="users" type="User">
        <id column="uid" property="id"></id>
        <result column="uname" property="username"></result>
        <result column="address" property="address"></result>
        <result column="birthday" property="birthday"></result>
        <result column="password" property="password"></result>
        <result column="sex" property="sex"></result>
        <!--映射List<Account> accountList
            coulmn :属性对应的列
        -->
        <collection property="accountList" ofType="account" column="uid"
        select="com.itheima.dao.AccountDao.findByUserId" fetchType="lazy"></collection>
    </resultMap>

    <select id="findAll" resultMap="users">
      select * from user
    </select>
</mapper>
5.AccountDao.xml
<mapper namespace="com.itheima.dao.AccountDao">
    <select id="findByUserId" resultType="account" parameterType="int">
        select * from account where u_id = #{userId}
    </select>
</mapper>
d、开启全局的延迟加载
<!--核心配置文件的全局的设置-->
<settings>
	<!--开启全局的延迟加载-->
	<setting name="lazyLoadingEnabled" value="true"/>
</settings>
十三、mybatis缓存
a、一级缓存
package com.itheima;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

/**
 * 一级缓存
 *  1,在同一sqlSession对象范围下,两次执行同一个sql语句,第二层没有执行sql语句,说明缓存的存在
 *  2.如果执行了增删改,提交操作,会清空缓存
 *  3. sqlSession.clearCache();清空缓存
 *  4. 一级缓存是SqlSession级别的, 必须是在一个sqlsession对象范围下才可以的得到一级缓存
 *
 * 一级缓存运行流程
 *  第一次执行sql语句,查询到数据,会在一级缓存中存储sql语句和数据,以 sql语句为key值, 以数据为value值
 *  在第二层执行sql语句时,会先从缓存中查询 ,以sql为key查询,得到数据,直接返回,如果没有相应的sql语
 *  句,则查询数据库
 *
 */
public class TestMybatisOTMLazy {

    @Test
    public void test(){
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mybatis-config.xml");
        //SqlSession工厂对象:单例模式
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserDao userDao1 = sqlSession.getMapper(UserDao.class);

        List<User> userList1 = userDao1.findAll();
        for (User user : userList1) {
            System.out.println(user);
        }
        sqlSession.close();
        //删除操作
//        UserDao  userDao2 = sqlSession.getMapper(UserDao.class);
//        userDao2.del(14);
//        sqlSession.commit();
        //清空缓存
//        sqlSession.clearCache();

        SqlSession sqlSession2 = sqlSessionFactory.openSession();
        UserDao  userDao3 = sqlSession2.getMapper(UserDao.class);
        List<User> userList3 = userDao3.findAll();
        for (User user : userList3) {
            System.out.println(user);
        }

        sqlSession2.close();
    }
}

b、二级缓存
package com.itheima;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

/**
 * 二级缓存
 *   1. 是sessionFactory级别的, 可以在多个SqlSession对象共享缓存数据
 *   2. 默认的是开启的
 *      <setting name="cacheEnabled" value="true"/>
 *   3. 在需要使用二级缓存的配置映射文件中开启
 *      <cache/>
 *   4. 需要在二级缓存中保存的pojo对象必须实现序列化接口
 *       User  implements Serializable
 *   5. 在同一namespace范围下,执行提交操作,会清空该namespace的缓存
 *   
 * 二级缓存的工作流程
 *     1,在任意一个sqlSession对象中执行了sql查询语句,当关闭sqlSession对象时,在二级缓存中保存数据:以 namespace.sql语句为key值
 *      以对象为value存储
 *     2. 当其他sqlSession对象执行时, 需要根据namespace.sql 查询是否存在缓存
 *      
 *  
 */
public class TestMybatisOTMLazy {

    @Test
    public void test(){
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mybatis-config.xml");
        //SqlSession工厂对象:单例模式
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserDao userDao1 = sqlSession.getMapper(UserDao.class);

        List<User> userList1 = userDao1.findAll();
        for (User user : userList1) {
            System.out.println(user);
        }
        sqlSession.close();

        SqlSession sqlSession2 = sqlSessionFactory.openSession();
        UserDao  userDao2 = sqlSession2.getMapper(UserDao.class);
        List<User> userList2 = userDao2.findAll();
        for (User user : userList2) {
            System.out.println(user);
        }

        sqlSession2.close();

        SqlSession sqlSession3 = sqlSessionFactory.openSession();
        UserDao  userDao3 = sqlSession3.getMapper(UserDao.class);
        List<User> userList3 = userDao3.findAll();
        for (User user : userList3) {
            System.out.println(user);
        }

        sqlSession3.close();
    }
}

十四、mybatis注解开发
a、实现增删改查
package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserDao {

    /**
     * 查询所有
     * @return
     */
    @Select("select * from user")
//    @Results 映射结果集, value = @Result 数组对象
//    @Result 映射列名与属性名不一样的
//           id 的默认值是false 默认为非主键
//    id=true 指定该列为主键
//    注解中:只需要写列名与属性名不一样的,一样的可以不写
//    特殊情况: 如果某列数据使用了两次或者两次以上,则两次映射都需要写出来
    @Results({
            @Result(id=true, column = "uid",property = "id"),
            @Result(column = "uname",property = "username")

    })
    public List<User> findAll();

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Select("select * from user where uid=#{id}")
    public User findById(Integer id);

    /**
     * 根据姓名模块查询
     * @param username
     * @return
     */
    @Select("select * from user where uname like \"%\"#{username}\"%\" ")
    public List<User> findByUsername(String username);

    /**
     * 查询总的记录数
     * @return
     */
    @Select("select count(*) from user")
    public Integer findTotalCount();

    /**
     * 添加用户
     * @param user
     */
//    保存获取主键(主键回显): @SelectKey   在oracle中会使用
//    keyProperty: 主键的属性名
//    keyColumn :主键列名
//    resultType: 主键的类型
//    before=false : 不是在添加之前, 添加之后查询
//    before=true : 在添加之前查询
//    statement: 需要执行的sql语句
//    select last_insert_id() :最后一次执行添加生成的主键
    /**
     *  在xml 主键回显
     *  <selectKey keyColumn="uid" keyProperty="id" resultType="int" order="AFTER">
            select last_insert_id()
         </selectKey>
     */
    @SelectKey(keyProperty = "id",keyColumn = "uid",resultType = Integer.class,before = false,
    statement = "select last_insert_id()")
    @Insert("insert into user values(null ,#{username},#{password},#{sex},#{address},#{birthday})")
    public void insert(User user);

    /**
     * 更新用户
     * @param user
     */
    @Update("update user set uname = #{username}, password=#{password}, sex = #{sex}" +
            ",address=#{address},birthday = #{birthday} where uid = #{id}")
    public void update(User user);

    /**
     * 删除用户
     * @param id
     */
    @Delete("delete from user where uid = #{id}")
    public void del(Integer id);
}

b、实现一对一
1. Account.java
public class Account {

    private Integer id;
    private String name;
    private Float money;
    private Integer u_id;
//    一个账户对应一个用户
    private User user;
}
2. AccountDao.java
public interface AccountDao {

    /**
     * 查询全部账户(包含用户信息)
     *
     *  one = @One(select = "" , fetchType=""):对应一个对象
     *          select 属性:mapperId = namespace.id
     *
     *           fetchType = FetchType.LAZY:提取方式为延迟加载,默认是立即加载
     *  Many: 对应多个对象
     *
     *
     * @return
     */
    @Select("select * from account")
    @Results({
            @Result(property = "user", column = "u_id",javaType = User.class,
                    one = @One(select = "com.itheima.dao.UserDao.findById", fetchType = FetchType.LAZY))
    })
    public List<Account> findAll();
}
3.UserDao.java
public interface UserDao {

    /**
     * 根据id查询一个用户对象
     * @param id
     * @return
     */
    @Select("select * from user where uid = #{id}")
    @Results({
            @Result(id = true,column = "uid" ,property = "id"),
            @Result(column = "uname",property = "username")
    })
    public User findById(Integer id);
}
c、实现一对多
1. User.java
public class User {
    private Integer id;
    private String username;
    private String address;
    private String password;
    private Date birthday;
    private String sex;

//    一个用户对应多个账户
    private List<Account> accountList;
 }
2. UserDao.java
public interface UserDao {

    /**
     * 查询所有的用户对象(包含账户信息)
     *
     *  @Result(property = "accountList", column = "uid", javaType = List.class,
            many = @Many(select = "com.itheima.dao.AccountDao.findByUserId",fetchType = FetchType.LAZY))


        javaType = List.class,可以省略


        <collection property="accountList" column="uid" ofType="Account"
            select="com.itheima.dao.AccountDao.findByUserId" fetchType="lazy">
        </collection>

     * @return
     */
    @Select( "select * from user")
    @Results({
            @Result(id=true, column = "uid" ,property = "id"),
            @Result(column = "uname",property = "username"),
            @Result(property = "accountList", column = "uid", javaType = List.class,
            many = @Many(select = "com.itheima.dao.AccountDao.findByUserId",fetchType = FetchType.LAZY))
    })
    public List<User> findAll();
}

3. AccountDao.java
public interface AccountDao {

    /**
     * 根据userId获取账户信息
     * @param userId
     * @return
     */
    @Select("select * from account where u_id = #{userId}")
    public List<Account> findByUserId(Integer userId);
}

d、动态sql
1. UserDao.java
public interface UserDao {

    /**
     * 根据姓名模糊查询,性别等于查询
     *
     * Provider:提供者
     * @SelectProvider: sql语句提供者
     *
     * Type: sql语句提供者的类的字节码
     * method: 提供者类中的方法
     * @return
     */
//    @Select("select * from user where sex = #{sex} and uname like \"%\"#{username}\"%\"   ")
    @SelectProvider(type = UserSqlProvider.class ,method = "findAll")
    @Results({
            @Result(id=true, column = "uid",property = "id"),
            @Result(column = "uname",property = "username")

    })
    public List<User> findByCondition(User user);

}

2. UserSqlProvider.java
/**
 * user sql 语句的提供者
 *
 * 在匿名内部类中访问的局部变量必须是final修饰的局部变量
 *  jdk 1.8以上版本,会默认添加final
 *  jdk 1.7以下版本,必须手动添加final
 */
public class UserSqlProvider {

    public String findAll(User user){
        StringBuffer sb = new StringBuffer();
        sb.append("select * from user where 1 = 1 ");
        if(user.getSex() != null){
            sb.append(" and sex = #{sex} ");
        }
        if(user.getUsername() != null){
            sb.append(" and uname like \"%\"#{username}\"%\" ");
        }

        return sb.toString();
    }
}

Mybatis推荐书籍

以下是一些关于 MyBatis 的书籍推荐及其推荐理由:

1.《MyBatis技术内幕》:这本书讲解了 MyBatis 的核心原理和实现细节,适合想要深入了解 MyBatis 的同学。
2.《MyBatis实战》:这本书通过实例演示了如何使用 MyBatis 进行数据库操作,适合初学者入门。
3.《MyBatis从入门到精通》:这本书从基础到高级全面介绍了 MyBatis 的使用,适合想要系统学习 MyBatis 的同学。
4.《MyBatis源码解析》:这本书详细分析了 MyBatis 的源代码,并讲解了其实现原理,适合想要深入研究 MyBatis 的同学。
5.《MyBatis开发经验谈》:这本书分享了一些作者在实际项目中使用 MyBatis 的经验和技巧,适合有一定经验的开发人员参考。

希望对你有所帮助~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TorlesseLiang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值