mybatis学习第二天

177 阅读3分钟

入门注解案例

把XML文件移除,在Dao接口的方法上使用@Selector注解,并且指定SQL语句同时需要在SqlMapConfig文件中的mapper配置是,使用class属性指定dao接口的全限定类名。

Dao实现类的方法太复杂。namespace和id很重要。

// 入门案例
public static void main(String[] args) throws Exception {
    // 1 读取配置文件
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
	绝对路径:d://xxx/xxx
    相对路径:src/java/xxx.xml
    
	读取配置文件
	1 使用类加载器 只能读取类路径的配置文件
	2 使用servletContext对象的getRealPath() 

    // 2 创建SqlSessionFactory工厂
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(in);

	创建工厂mybatis使用了构建者模式 builder 构建者 对象的创建细节隐藏 使用者直接调用即可拿到对象

    // 3 使用工厂生成一个SqlSession对象
    SqlSession sqlSession = factory.openSession();

	工厂模式 解耦

    // 4 使用SqlSession创建Dao接口的代理对象
    UserInterFace userInterFace = sqlSession.getMapper(UserInterFace.class);

	代理模式 不修改源码对已有方法增强

   
    // 5 使用代理对象执行方法
    List<User> users = userInterFace.findAll();
    for (User user: users) {
        System.out.println(user);
    }
    // 6 释放资源
    sqlSession.close();
    in.close();
}

自定义Mybatis分析

mybatis使用代理dao的方式实现增删改查处理:

1 创建代理对象

2 在代理对象中调用selectList

			1 连接数据库信息 创建Connetion对象
            <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/htoa?serverTimezone=GMT"/>
            <property name="username" value="root"/>
            <property name="password" value="htoa"/>

			2 映射配置信息
			<mappers>

			<mapper resource="com/mybatis/dao/User.xml"></mapper>

			</mappers>
			
			3 执行的SQL语句获取prepareStatement
			封装的实体类全限定类名
			<mapper namespace="com.mybatis.dao.UserInterFace">
			<!--    配置查询所有 id 方法名称-->
			<select id="findAll" resultType="com.mybatis.domain.User">
   			 select * from user
			</select>
			</mapper>

4 读取配置文件:用到的技术就是解析XML的技术。 使用dom4j解析XML技术

5

1)根据配置文件信息创建Connection对象

注册驱动 获取连接

2)获取预处理对象PreparedStatement

此时需要SQL语句

conn.preparedStatement(sql)

  1. 执行查询

    ResultSet aa = preparedStatement.executeQuery();

  2. 遍历结果集用于封装 使用反射封装

    List list = new ArrayList();

    while (aa.next()) {

    E element = (E)Class.forName(配置的全限定类名).newInstance()

    进行封装

    实体类属性和表的列名是一致的 把表的列名看成是实体类的属性名称。反射的方式来根据名称获取属性,并把值赋进去。

    加入list

    }

5)return list

执行selectList方法:需要给方法提供两个信息。

1 连接信息

2 映射信息

包含两部分: 1)执行的SQL语句 2)封装结果的实体类的全限定类名。这两个信息组合定义成对象。

Mapper: key:com.mybatis.dao.UserInterFace.findAll value:mapper对象 String sql + String domainClassPath

6

   // 4 使用SqlSession创建Dao接口的代理对象

    UserInterFace userInterFace = sqlSession.getMapper(UserInterFace.class);

根据Dao接口的字节码创建Dao的代理对象 public getMapper(Class daoInterfaceClass) {

类加载器:使用的和被代理对象是相同的类加载器

代理对象要实现的接口:和被代理对象实现相同的接口 如何代理:增强的方法 InvocationHandler的接口,写该接口的实现类,在实现类调用selectList方法

Proxy.newProxyInstance(类加载器,代理对象要实现的接口字节码数组, 如何代理)

}

7 自定义mybatis入门能看到的类

class Resources

class SqlSessionFactoryBuilder

interface SqlSessionFactory

interface SqlSession