MyBatis查询所有的对象
创建dao接口IStudent:
?
package com.ibatis.dao;
?
import java.util.List;
import com.ibatis.model.Student;
public interface IStudentDAO {
?public void addStudent(Student stu);
?public void addStudentBySequence(Student stu);
?public void deleteStudentById(int id);
?public void updateStudent(Student stu);
?public List<Student> queryAllStudents();
?public List<Student> queryStudentsByName(String name);
?public Student queryStudentById(int id);
}
?
---------------------------------------------
改写Student.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.ibatis.dao.IStudentDAO">
?
?<select id="selectAllStudents"?resultType="Student">
??select * from student
?</select>
?
</mapper>
---------------------------------------------
创建Ibatis DAO实现类:
?
package com.ibatis.dao.impl;
?
import java.io.IOException;
import java.io.Reader;
import java.util.List;
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 com.ibatis.dao.IStudentDAO;
import com.ibatis.model.Student;
public class IStudentDAOIbatisImpl implements IStudentDAO {
?SqlSession sqlSession = null;
?static SqlSessionFactory sf;
?static{
??Reader reader = null;
??try {
???reader = Resources.getResourceAsReader("com/ibatis/SqlMapConfig.xml");
??} catch (IOException e) {
???e.printStackTrace();
??}
???sf = new SqlSessionFactoryBuilder().build(reader);
?}
?
??public List<Student> queryAllStudents() {
??List<Student> students;
??try{
???sqlSession = sf.openSession();
???students = sqlSession.selectList("selectAllStudents");
??}finally{
???sqlSession.close();
??}
??return students;
?}
?
}
-------------------------------------------------------
创建junit测试:
public class IStudentDAOIbatisImplTest {
?@Test
?public void queryAllStudentsTest(){
??IStudentDAO sDAO = new IStudentDAOIbatisImpl();
??List<Student> students = sDAO.queryAllStudents();
??System.out.println(students);
?}
}