MyBatis的简单测试

首先需要一个实体model User,并生成了所有成员变量的get、set方法及toString方法。

package self.exercise.bean;

public class User {

    private String account;

    private int id;

    private String password;

    private String user_name;

    public User() {
    }

    public User(String account, String password, String user_name) {
        super();
        this.account = account;
        this.password = password;
        this.user_name = user_name;
    }
}

数据库中的web表中的字段与User类中的变量一 一对应。

MyBatis实现对数据库数据的操作有两种方式,根据namespace+id的比较传统的方式,以及根据可以合理描述参数和返回值的接口进行代理。

一、传统方式

在映射文件中插入

<mapper namespace="self.exercise.dao">
     <select id="load" resultType="self.exercise.bean.User">
        select * from user where id = 1;
    </select>
</mapper>

请保证namespace的值是唯一的。resultType中指定了User类所在的包。

在核心配置文件中的mappers标签中插入,将映射文件与核心配置文件建立联系。

<mapper resource="self/exercise/mapper/UserMapper.xml" />

从 XML 中构建 SqlSessionFactory

每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。

从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。但是也可以使用任意的输入流(InputStream)实例,包括字符串形式的文件路径或者 file:// 的 URL 形式的文件路径来配置。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,可使从 classpath 或其他位置加载资源文件更加容易。

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

从 SqlSessionFactory 中获取 SqlSession

既然有了 SqlSessionFactory ,我们就可以从中获得 SqlSession 的实例了。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。例如:

sqlSession = sqlSessionFactory.openSession();
try{
  User user = sqlSession.selectOne("self.exercise.dao.load");
}finally{
  sqlSession.close();
}

二、接口代理

新建一个代理接口UserDao

package self.exercise.dao;

import self.exercise.bean.User;

public interface UserDao {
    User load();
}

此时,映射文件中的namespace必须是接口的路径,即self.exercise.dao.UserDao

在测试代码中将namespace+id方式替换为

sqlSession = sqlSessionFactory.openSession();
try{
     User user = sqlSession.getMapper(UserDao.class).load();
}finally{
  sqlSession.close();
}

另外,定制化SQL语句也可在接口中用注解方式实现,替代XML中select标签的内容,例如:

package self.exercise.dao;

import org.apache.ibatis.annotations.Select;

import self.exercise.bean.User;

public interface UserDao {
    @Select("select * from user where id = 1;")
    User load();
}

注解方式还是XML方式,传统方式还是接口代理;可灵活搭配使用。

原文地址:https://www.cnblogs.com/qingyaxuan/p/6395867.html