现在有一个数据库叫 Student , 建一个实体类来映射它
package pojo;public class Student {int id;int studentID;String name;/* getter and setter */}
在它隔壁建Student.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="pojo"><select id="listStudent" resultType="pojo.Student">select * from student</select></mapper>
可以来一个测试类
package test;
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 pojo.Student;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestMyBatis {
public static void main(String[] args) throws IOException {
// 根据 mybatis-config.xml 配置的信息得到 sqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 然后根据 sqlSessionFactory 得到 session
SqlSession session = sqlSessionFactory.openSession();
// 最后通过 session 的 selectList() 方法调用 sql 语句 listStudent
List<Student> listStudent = session.selectList("listStudent");
for (Student student : listStudent) {
System.out.println("ID:" + student.getId() + ",NAME:" + student.getName());
}
}
}
