Mybatis自定义框架基础学习篇

1,自定义Mybatis框架接口分析

image-20200706114059732

2,入门基础框架的分析

image-20200706114718474

MybatisUtils代码:

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
//    既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
//    SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
//    你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

MybatisTest测试类代码

public class MybatisTest {
    public static void main(String[] args) throws IOException {
        // 第一步:读取配置文件
        //InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 第二步:创建SqlSessionFactory工厂
        // SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // SqlSessionFactory factory = builder.build(in);
        //简化后
        //SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

//---------------------------------------------------------------------------
//   对以上代码进行封装到MybatisUtils后,代码更简洁

        // 第三步:创建SqlSession
        SqlSession session = MybatisUtils.getSqlSession();
        // 第四步:创建Dao接口的代理对象
        UserDao userDao = session.getMapper(UserDao.class);
        // 第五步:执行dao中的方法
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
        // 第六步:释放资源
        session.close();

    }
}

使用注解开发代码

public interface UserDao {
    @Select("select * from user")
    List<User> findAll();
}

使用xml配置文件开发代码

<mapper namespace="com.xxx.dao.UserDao">
<!--    配置查询所有-->
    <select id="findAll" resultType="com.xxx.domain.User">
        select * from user ;
    </select>
</mapper>

两者的对比

image-20200706115929849

posted @ 2020-07-06 12:09  like3ong  阅读(152)  评论(0编辑  收藏  举报