映射器创建在dao包中。
public interface StudentMapper{ public Student findByName(String Name); }映射器配置文件应与映射器在同一目录下,建议与映射器同名. StudentMapper.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"> <mapper namespace="com.dao.StudentMapper"> <select id="findByName" parameterType="String" resultType="com.domain.Student"> select * from student where Name=#{Name}; </select> </mapper>测试有两种方法: - 使用Test注释进行测试 首先,为工程添加单元测试类库: 大致步骤:选中项目之后,右键点击Build Path ->Add Library->JUnit之后一直下一步。然后创建一个新的测试类用于测试:
public class TestStudent{ /* 在进行测试时,大致步骤如下: 1.读取配置文件. 2.创建SqlSessionFactory工厂. 3.获取mapper映射器. 4.调用mapper相应的方法,得到相应的结果. 5.提交事务(CRUD中除去查询外,均需要进行事务提交) 6.关闭sqlSession. 7.打印结束语句(用户判断是否结束测试,非必要的) */ @Test public void Test() throw IOException{ Reader reader = Resources.getResourceAsReader("mybatis.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); System.out.println(studentMapper.findByName("李某某")); sqlSession.close(); System.out.println("END"); } }之后敲击shift+alt+X +T进行单元测试。 - 也可以通过写一个main方法进行测试 main方法内的代码与使用单元测试使用的代码是一样的。
public static void main(String args[]){ Reader reader = Resources.getResourceAsReader("mybatis.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); System.out.println(studentMapper.findByName("李某某")); sqlSession.close(); System.out.println("END"); }