首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

MyBatis查询全部的对象

2012-07-01 
MyBatis查询所有的对象创建dao接口IStudent:?package com.ibatis.dao?import java.util.Listimport com.

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);
?}

}

热点排行