Mybatis笔记-Mapper动态代理开发

什么是Mapper动态代理开发

Mapper动态代理开发只需要编写对应的Mapper接口(相当于Dao接口)和对应的xml文件,然后mybatis会根据接口定义创建接口的动态代理对象,动态代理对象的方法体就相当于Dao接口的实现类方法。
Mapper动态代理开发需要遵循以下规范:

  1. 映射文件的namespace需要为接口的全类路径名(com.tesst.www.mapper.UserMapper)
  2. 接口的方法名需要与映射文件中定义的每一个statement的ID相同
  3. 接口的方法输入参数需要与对应statement的sql语句的parameterType相同
  4. 接口的方法输出参数需要与对应statement的sql语句的resultType相同或List

代码演示

Mapper接口

第一步是配置Mapper接口,接口名为UserMapper,演示 增删改查 以及 关联查询

package com.tesst.www.mapper;

import java.util.List;

import com.tesst.www.po.User;
/**
 * MyBatis代理开发
 * @author Lonely
 *
 */
public interface UserMapper {
/**
 * 查询所有用户信息
 * @return
 */
public List<User> queryUser();

/**
 * 新增用户
 * @param user
 * @return
 */
public boolean insertUser(User user);

/**
 * 根据ID删除用户
 * @param id
 * @return
 */
public boolean deleteUserById(int id);

/**
 * 更改用户信息
 * @param user
 * @return
 */
public boolean updateUserById(User user);

/**
 * 查询用户信息 关联查询用户购买的商品信息
 * @return
 */
public List<User> queryUserAndItems();
}

配置XML文件

<?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.tesst.www.mapper.UserMapper">

    <!-- 查询所有用户信息 -->
    <select id="queryUser" resultType="user">
        <!-- Mybatis中sql语句尾部不用加分号 -->
        select id,username,password,power from user
    </select>

    <!-- 新增用户 -->
    <insert id="insertUser" parameterType="user">
        insert into user
        values(#{id},#{username},#{password},#{power})
    </insert>

    <!-- 删除用户 -->
    <delete id="deleteUserById" parameterType="int">
        delete from user where
        id=#{kkid}
    </delete>

    <!-- 修改用户信息 -->
    <update id="updateUserById" parameterType="user">
        UPDATE `user` SET
        username=#{username},`password`=#{password},power=#{power} WHERE
        id=#{id}
    </update>

<!-- 查询用户信息 关联查询用户购买的商品信息 多表联查 -->
<!-- User实体类中创建orders实体类对象 orders实体类对象中创建orderdetail实体类对象 以此类推 -->
<resultMap type="user" id="useranditemsbyid">
    <id column="u_uid" property="uid"/>
    <result column="u_user" property="username"/>
    <result column="u_birthday" property="birthday"/>
    <result column="u_sex" property="sex"/>
    <result column="u_address" property="address"/>
    <collection property="orders" ofType="com.tesst.www.pojo.Orders">
        <id column="o_id" property="id"/>
        <result column="o_userid" property="user_id"/>
        <result column="o_number" property="number"/>
        <result column="o_createtime" property="createtime"/>
        <result column="o_note" property="note"/>
        <collection property="orderdetail" ofType="com.tesst.www.pojo.Orderdetail">
            <id column="od_id" property="id"/>
            <result column="od_ordersid" property="orders_id"/>
            <result column="od_itemsid" property="items_id"/>
            <result column="od_itemsnum" property="items_num"/>
            <association property="items" javaType="com.tesst.www.pojo.Items">
                <id column="i_id" property="id"/>
                <result column="name" property="i_name"/>
                <result column="i_price" property="price"/>
                <result column="i_detail" property="detail"/>
                <result column="i_pic" property="pic"/>
                <result column="i_createtime" property="createtime"/>
            </association>
        </collection>
    </collection>
</resultMap>

<select id="finduseranditems" resultMap="useranditemsbyid">
SELECT
    `user`.uid u_uid,
    `user`.username u_user,
    `user`.birthday u_birthday,
    `user`.sex u_sex,
    `user`.address u_address,
    orders.id o_id,
    orders.user_id o_userid,
    orders.number o_number,
    orders.createtime o_createtime,
    orders.note o_note,
    orderdetail.id od_id,
    orderdetail.orders_id od_ordersid,
    orderdetail.items_id od_itemsid,
    orderdetail.items_num od_itemsnum,
    items.id i_id,
    items.`name` i_name,
    items.price i_price,
    items.detail i_detail,
    items.pic i_pic,
    items.createtime i_createtime 
FROM
    `user`,
    orders,
    orderdetail,
    items
WHERE
    `user`.uid = orders.user_id 
    AND orders.id = orderdetail.orders_id 
    AND orderdetail.items_id = items.id
</select>
</mapper>

配置SqlMapConfig

<configuration>
        <!-- 加载.properties配置文件 -->
        <properties resource="db.properties"></properties>
        
        <!-- 定义映射对象的别名 -->
        <typeAliases>
            <package name="com.tesst.www.po"/>
        </typeAliases>

        <!-- 采用jdbc提供的数据源连接池 -->
        <environments default="development">
            <environment id="development">
            <!-- 使用jdbc事务管理-->
                <transactionManager type="JDBC" />
            <!-- 数据库连接池-->
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}" />
                    <property name="url" value="${url}" />
                    <property name="username" value="${user}" />
                    <property name="password" value="${pwd}" />
                </dataSource>
            </environment>
        </environments>
        
        <!-- 加载mapper映射文件到全局配置文件 -->
        <mappers>
        <package name="com.tesst.www.mapper"/>
        </mappers>        
</configuration>

SqlSession工厂单例模式

 //SqlSessionFactory单例设计
public class SqlSessionFactorySingletion {
    private static SqlSessionFactory sqlSessionFactorySingletion;

    // 私有化构造方法
    private SqlSessionFactorySingletion() {
    };

    // DCL双锁机制 保证线程安全
    public static SqlSessionFactory getInstance() throws Exception {
        if (sqlSessionFactorySingletion == null) {
            synchronized (SqlSessionFactorySingletion.class) {
                if (sqlSessionFactorySingletion == null) {
                    InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
                    sqlSessionFactorySingletion = new SqlSessionFactoryBuilder().build(inputStream);
                }
            }
        }
    return sqlSessionFactorySingletion;
    }
}

测试类

public class UserTest {
    @Test
    public void usertest1() throws Exception {

        SqlSession sqlsession = SqlSessionFactorySingletion.getInstance().openSession();
        UserMapper mapper = sqlsession.getMapper(UserMapper.class);
        List<User> user = mapper.queryUser();
        System.out.println(user);

        // 关闭SqlSession
        sqlsession.close();
    }

    @Test
    public void usertest2() throws Exception {

        SqlSession sqlsession = SqlSessionFactorySingletion.getInstance().openSession();
        UserMapper mapper = sqlsession.getMapper(UserMapper.class);

        User user = new User();
        user.setId(0);
        user.setUsername("测试2");
        user.setPassword("asdqwe");
        user.setPower(1);
        mapper.insertUser(user);

        //事务
        sqlsession.commit();
        // 关闭SqlSession
        sqlsession.close();
    }

    @Test
    public void usertest3() throws Exception {

        SqlSession sqlsession = SqlSessionFactorySingletion.getInstance().openSession();
        UserMapper mapper = sqlsession.getMapper(UserMapper.class);
        mapper.deleteUserById(10);

           //事务
        sqlsession.commit();
        // 关闭SqlSession
        sqlsession.close();
    }
    @Test
    public void usertest4() throws Exception{
        SqlSession sqlsession = SqlSessionFactorySingletion.getInstance().openSession();
        UserMapper mapper = sqlsession.getMapper(UserMapper.class);
        
        User user = new User();
        user.setId(7);
        user.setUsername("test2");
        user.setPassword("asdqwe");
        user.setPower(1);
        mapper.updateUserById(user);
        
        sqlsession.commit();
        // 关闭SqlSession
        sqlsession.close();
    }

添加新评论