MyBatis框架入门案例分享(二)

81 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第5天,点击查看活动详情

(7) 创建StudentDaoImpl.xml文件

右键新建StudentDaoImpl.xml文件,从MyBatis-3-User-Guide-Simplified-Chinese.pdf中拷贝过来头参数.

该文件完成数据库中student表的所有增删改查的操作.

右键新建StudentDaoImpl.xml文件,从MyBatis-3-User-Guide-Simplified-Chinese.pdf中拷贝过来头参数.

该文件完成数据库中student表的所有增删改查的操作.

< mapper namespace=”自定义的路径名称”>,在简单访问中namespace中的内容可以自定义,目的是为了区别不同< mapper>中相同id的语句.

该文件中提供< select>< update>< insert>< delete>等数据库中的基本操作标签.

1653897912003.jpg

(8) 创建测试类

使用Junit单元测试完成各种功能测试.

使用@Before注解来进行所有测试前的SqlSession的创建工作.

使用@After注解来进行所有测试方法执行后的关闭SqlSession的工作.

使用@Test注解来验证每一个功能的实现

public class MyTest {\
    SqlSession session;
    @Before\
    public void openSession()throws Exception{\
        //创建文件流,读取SqlMapConfig.xml\
        InputStream inputStream = Resources.*getResourceAsStream*("SqlMapConfig.xml");\
        //创建SqlSessionFactory\
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);\
        //取得SqlSession\
        session = factory.openSession();\
    }\
    @Test\
    public void testSelectStudentAll()throws Exception{\
        List<Student> list = session.selectList("com.bjpowernode.selectStudentAll");\
        list.forEach(stu-> System.*out*.println(stu));\
    }\
    @Test\
    public void testStudentGetById(){\
        Student stu = session.selectOne("com.bjpowernode.selectStudentById",2);\
        System.*out*.println(stu);\
    }\
    @Test\
    public void testSelectStudentByEmail(){\
        List<Student> list = session.selectList("com.bjpowernode.selectStudentByEmail","l");\
        list.forEach(stu-> System.*out*.println(stu));\
    }\
    @Test\
    public void testInsertStudent(){\
        Student stu = new Student("李四四","23234@qq.com",22);\
        int num = session.insert("com.bjpowernode.insertStudent",stu);\
        //切记切记切记:因为我们的事务管理机制使用的是JDBC,所以所有的增删改查后,要手工提交事务\
        //session.commit();\
        session.commit();//手工提交事务\
        System.*out*.println(num);\
    }\
    @After\
    public void closeSession(){\
        session.close();\
    }\
}

2.3 MyBatis对象分析

(1) Resources类

Resources 类,顾名思义就是资源,用于读取资源文件。其有很多方法通过加载并解析资源文件,返回不同类型的 IO 流对象。

(2) SqlSessionFactoryBuilder类

SqlSessionFactory 的 创 建 , 需 要 使 用 SqlSessionFactoryBuilder 对 象 的 build() 方 法 。 由 于SqlSessionFactoryBuilder对象在创建完工厂对象后,就完成了其历史使命,即可被销毁。所以,一般会将该 对象创建为一个方法内的局部对象,方法结束,对象销毁。

(3) SqlSessionFactory接口

SqlSessionFactory 接口对象是一个重量级对象(系统开销大的对象),是线程安全的,所以一个应用只需要一个该对象即可。创建 SqlSession 需要使用 SqlSessionFactory 接口的的 openSession()方法。

A. openSession(true):创建一个有自动提交功能的 SqlSession

B. openSession(false):创建一个非自动提交功能的 SqlSession,需手动提交

C. openSession():同 openSession(false)

(4) SqlSession接口

SqlSession  接口对象用于执行持久化操作。一个 SqlSession  对应着一次数据库会话,一次会话以SqlSession 对象的创建开始,以 SqlSession 对象的关闭结束。

SqlSession 接口对象是线程不安全的,所以每次数据库会话结束前,需要马上调用其 close()方法,将其关闭。再次需要会话,再次创建。 SqlSession 在方法内部创建,使用完毕后关闭。