本文共 2735 字,大约阅读时间需要 9 分钟。
1.在resources/mapper目录里创建学生映射器配置文件 - StudentMapper.xml
package net.zjs.mybatis.mapper;/* * 功能:学生映射器接口 * */import net.zjs.mybatis.bean.Student;import java.util.List;import java.util.Map;public interface StudentMapper { ListfindByCondition(Map condition);}
package net.zjs.mybatis.mapper;import net.zjs.mybatis.bean.Student;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.After;import org.junit.Before;import org.junit.Test;import java.io.IOException;import java.io.Reader;import java.util.HashMap;import java.util.List;import java.util.Map;public class TestStudentMapper { private SqlSession sqlSession; // SQL会话 private StudentMapper studentMapper; // 学生映射器 @Before public void init() { try { // 读取MyBatis配置文件作为字符输入流 Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); // 基于MyBatis配置文件构建SQL会话工厂 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader); // 利用SQL会话工厂获取SQL会话 sqlSession = factory.openSession(); // 利用SQL会话获取学生映射器对象 studentMapper = sqlSession.getMapper(StudentMapper.class); // 提示用户SQL会话对象创建成功 System.out.println("sqlSession对象已创建。"); } catch (IOException e) { e.printStackTrace(); } } @Test public void testFindByCondition(){ Mapcondition=new HashMap<>(); condition.put("gender","女"); List students = studentMapper.findByCondition(condition); students.forEach(student -> System.out.println(student)); } @After public void destroy() { // 关闭SQL会话 sqlSession.close(); // 提示用户SQL会话对象关闭 System.out.println("sqlSession对象已关闭。"); }}
修改测试方法里的查询条件
运行测试方法testFindByCondition(),查看结果
修改测试方法里的查询条件
运行测试方法testFindByCondition(),查看结果
转载地址:http://hjtki.baihongyu.com/