- 在接口StudentDao中新增一个方法
public Student findStuentById(int id);
完整源码:
package com.hbfu.dao;
import com.hbfu.entity.Student;
import java.util.List;
public interface StudentDao {
public List<Student> findAllStudent();//查找全部学生
//新增方法
public Student findStudentById(int id);
}
- 在映射文件StudentMapper.xml中新增一段select语句
<select id="findStudentById" parameterType="int" resultMap="studentResultMap">
select * from student where id=#{id}
</select>
完整源码:
<?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.hbfu.dao.StudentDao">
<!-- 配置结果映射 -->
<resultMap id="studentResultMap" type="com.hbfu.entity.Student">
<result property="sgender" column="gender"></result>
<result property="sage" column="age"></result>
</resultMap>
<!-- 查询 -->
<select id="findall" resultMap="studentResultMap">
select * from student
</select>
<!-- 查询单条语句 -->
<select id="findStudentById" parameterType="int" resultMap="studentResultMap">
select * from student where id=#{id}
</select>
</mapper>
- 在接口StudentDao的实现类StuedntDaoImpl中新增方法
@Override
public Student findStudentById(int id) {
Student student = new Student();
try {
SqlSession session = MyBatisUtil.getSession();
student = session.selectOne("com.hbfu.dao.StuentDao.findStudentById",id);
}catch (Exception e){
e.printStackTrace();
}
return student;
}
完整源码:
package com.hbfu.dao;
import com.hbfu.entity.Student;
import com.hbfu.util.MyBatisUtil;
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 java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class StudentDaoImpl implements StudentDao{
@Override
public List<Student> findAllStudent() {
SqlSession session = null;
List<Student> studentList=new ArrayList<Student>();
try {
session= MyBatisUtil.getSession();
studentList=session.selectList("com.hbfu.dao.StudentDao.findall");
}catch (Exception e){
e.printStackTrace();
}
return studentList;
}
//新增一个查询单条记录方法
@Override
public Student findStudentById(int id) {
Student student = new Student();
try {
SqlSession session = MyBatisUtil.getSession();
student = session.selectOne("com.hbfu.dao.StudentDao.findStudentById",id);
}catch (Exception e){
e.printStackTrace();
}
return student;
}
}
- 在测试类StuentTest中添加一个方法studentDao.findStudentById(int id)
System.out.println("通过id查询学生信息"+studentDao.findStudentById(2));
完整源码:
import com.hbfu.dao.StudentDao;
import com.hbfu.dao.StudentDaoImpl;
import com.hbfu.entity.Student;
import org.junit.Test;
public class StudentTest {
@Test//注解--测试方法,不需要写主方法就可以运行测试程序
public void test(){
StudentDao studentDao = new StudentDaoImpl();
System.out.println(studentDao.findAllStudent());
//新增一个输出语句--查询单条记录方法,并传入id
System.out.println("通过id查询学生信息"+studentDao.findStudentById(2));
}
}