Mybatis代理模式的基本了解

Mybatis的介绍

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
最大的特点是:动态sql语句,缓存技术。(替代hibernate框架)。

Mybatis开发的两种模式

**1.**编写Dao接口和Dao实现类的传统开发,实现类中注入SessionFactory,每个方法内部创建SqlSession,调用SqlSession的API,由于SqlSession是线程不安全的,所以SqlSession需要在每个方法内部创建,用完立即关闭,释放资源

public class Test {
    @org.junit.Test
    public  void test(){
    //读取核心配置文件
    //String path ="mybatis-config.xml";
    //得到一个输入流对象

 InputStream is;
  {
        try {
     	    SqlSession sqlSession = SqlSessionUtils.getSqlSessionUtils().sqlSession;         
            }
            //得到sqlSessionFactory
    SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
    //通过SqlSessionFactory 得到SqlSession
    SqlSession sqlSession =  ssf.openSession();*/
    //返回的一列,就用selectOne
  int num = sqlSession.selectOne("com.offcn.dao.UserMapper.selectCount");
            System.out.println(num);
          /* List<User> list = sqlSession.selectList("com.offcn.dao.UserMapper.selectAllUser");
           for (User u : list){
               System.out.println(u.getUserName()+"\t"+u.getUserPassword());
           }*/
            } catch (Exception e) {
            e.printStackTrace();
        }
      }
    }
}
            

Mybatis的执行过程:
1首先加载核心xml文件
2
通过加载这个xml核心文件,就能得到一个sqlSessionFactory
3*通过得到这个sqlSessionFactory来产生sqlSession 这个对象本身不能来操作我们的数据库
这个对象会产生一个解析器(excutor),可以得到一个mappedStatement
(也是Statement对象的子类)对象,就可以执行sql
最后给我们返回数据(map int list)
**2.**mapper代理方式,只编写Dao接口,不编写Dao实现类,具体实现类写在mapper.xml映射文件里面。

UserMapper接口

package com.offcn.dao;

import com.offcn.entity.Address;

import java.util.List;

public interface AddressMapper {
    //修改的操作
    int updateAddress(Address address);
    //增加
    int insertAddress(Address address);
    //删除
    int deleleAddress(int id);
    //根据id查
    Address selectById(int id);
    //查所有
    List<Address> selectAllAddress();
    //模糊查询
    List<Address> selectLikeAddress(String string);

}

UserMapper.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">
<!--namespace找到你关联的那个接口类 包名+接口名 相当于一个包,包管理器-->
<mapper namespace="com.offcn.dao.UserMapper">
    <!--这个id是唯一的,是你访问的一个标识符,查询中记录数,resultType代表其返回值类型
    id名字必须跟UserMapper里的方法名一样-->
    <select id="selectCount" resultType="int">
    select count(1) from smbms_user
    </select>

    <!--全查,resultType 可以给别名-->
    <select id="selectAllUser" resultType="com.offcn.entity.User">
        select * form smbms_user
    </select>
    <!--模糊查询 parameterType 这个参数的类型,#{userName}代表我们以前的?也就是占位符,模糊查询一定要加concat-->
    <select id="selectLikeUser" resultType="com.offcn.entity.User" parameterType="String">
    select * from smbms_user where userName like concat('%',#{userName},'%')
    </select>
    <!--通过id查找对象-->
    <select id="selectById" resultType="com.offcn.entity.User" parameterType="int">
        select * from smbms_user where id =#{id}
    </select>
    <!--根据id修改名字,返回值的类型可以不需要,第一个userName对应的是数据库的列名,
    第二个userName对应的是java的实体bean 建议和数据库里的属性一一对应上-->
    <update id="updateById" parameterType="com.offcn.entity.User">
        update smbms_user set userName=#{userName},userPassword=#{userPassword} where id=#{id}
    </update>
    <!--根据id删除信息-->
    <delete id="deleteById" parameterType="int">
        delete from smbms_user where id=#{id}
    </delete>
    <!--增加一个对象-->
    <insert id="insertUser" parameterType="com.offcn.entity.User">
        insert into smbms_user(userName,userPassword) values(#{userName},#{userPassword})
    </insert>

</mapper>

SqlSessionUtils工具类

package com.offcn.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtils {
    /**
     * 得到SqlSession
     */
    private static SqlSessionUtils sqlSessionUtils;
    public SqlSession sqlSession;

    private SqlSessionUtils() {
        String path = "mybatis-config.xml";
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream(path);

            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
            //设置为ture 代表默认提交事务
             sqlSession = ssf.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //提供一个对外的方法得到这个对象
    //synchronized 第一个锁方法(死锁) 保证只有一个线程能进入这个方法
    public static synchronized SqlSessionUtils getSqlSessionUtils() {
        if (sqlSessionUtils == null) {
            //锁类的原因:在java jvm 实例化对象(有四个步骤),避免当走到第一个步骤的时候,
            // 而另外的线程又开始实例化对象(保证永远只有一个这样的类)
            synchronized (SqlSessionUtils.class) {
                if (sqlSessionUtils == null) {
                    sqlSessionUtils = new SqlSessionUtils();
                }
            }
        }
        return sqlSessionUtils;
    }
}

测试类

package com.offcn.test;

import com.offcn.dao.AddressMapper;
import com.offcn.dao.UserMapper;
import com.offcn.entity.Address;
import com.offcn.entity.User;
import com.offcn.utils.SqlSessionUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.jws.soap.SOAPBinding;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;

public class Test {
    @org.junit.Test
    public  void test(){
     {
        try {
         SqlSession sqlSession = SqlSessionUtils.getSqlSessionUtils().sqlSession;
            List<User> list = sqlSession.getMapper(UserMapper.class).selectAllUser();
            for (User user:list){
                System.out.println(user.getUserName());
            }

       /*     List<Address> list = sqlSession.getMapper(AddressMapper.class).selectLikeAddress("n");
            for (Address address:list){
                System.out.println(address.getContact());
            }*/
      /*      List<Address> list = sqlSession.getMapper(AddressMapper.class).selectAllAddress();
            for (Address address:list){
                System.out.println(address.getContact());
            }*/
          /*  Address address = sqlSession.getMapper(AddressMapper.class).selectById(8);
            System.out.println(address.getContact());*/

           /* int sum = sqlSession.getMapper(AddressMapper.class).deleleAddress(9);
            System.out.println(sum);*/
         /* Address address = new Address();
          address.setContact("黄建斌222");
          address.setAddressDesc("浙江省乐清市222");
            int num = sqlSession.getMapper(AddressMapper.class).insertAddress(address);
            System.out.println(num);*/
       /*    address.setId(1);
            int sum = sqlSession.getMapper(AddressMapper.class).updateAddress(address);
            System.out.println(sum);*/


            /*  List<User> list = sqlSession.getMapper(UserMapper.class).selectAllUser();
            for (User user:list){
                System.out.println(user.getUserName()+"\t"+user.getUserPassword());
            }*/


            /*List<User> list = sqlSession.getMapper(UserMapper.class).selectAllUser();
            for (User user1:list){
                System.out.println(user1.getUserName()+"\t"+user1.getUserPassword());
            }*/
            } catch (Exception e) {
            e.printStackTrace();
        }
      }
    }
}

最终版的一个执行过程
1.首先加载xml文件
2.得到sqlSession
3.通过sqlSession得到接口类 调用其方法sqlSession.getMapper(*.Class).方法()
4.调用方法后会走到我们相应的UserMapper.xml
5.然后执行sql语句,返回结果集

在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值