Mybatis的CRUD

实体映射文件:

----------------------------------------------------------------

<?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>
 
 <select id="selectStudentById" parameterType="int" resultType="Student">
  select *
  from student
  where s_id = #{s_id}
 </select>
 
 <insert id="insertStudent" parameterType="Student">
  insert into student(s_id,s_name,s_age)
  values       (#{s_id},#{s_name},#{s_age})
 </insert>
 
 <delete id="deleteStudentById" parameterType="int">
  delete from student
  where s_id = #{s_id}
 </delete>
 
 <update id="updateStudentById" parameterType="Student">
  update student
  set s_name = #{s_name},
   s_age = #{s_age}
  where s_id = #{s_id}
 </update>
</mapper>

 

-------------------------------------------------

parameterType 传入参数类型

resultType 返回结果类型

-------------------------------------------------

调用:

 

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 void addStudent(Student stu) {
  try{
   sqlSession = sf.openSession();
   sqlSession.insert("insertStudent", stu);
   sqlSession.commit();//这里一定要提交,不然数据进不去数据库中
  }finally{
   sqlSession.close();
  }
 }

 public void addStudentBySequence(Student stu) {
  
 }

 public void deleteStudentById(int id) {
  try{
   sqlSession = sf.openSession();
   int returnValue = sqlSession.delete("deleteStudentById", id);
   System.out.println(returnValue);//受影响行数
   sqlSession.commit();//这里一定要提交,不然数据进不去数据库中
  }finally{
   sqlSession.close();
  }
 }

 public List<Student> queryAllStudents() {
  List<Student> students;
  try{
   sqlSession = sf.openSession();
   students = sqlSession.selectList("selectAllStudents");
  }finally{
   sqlSession.close();
  }
  return students;
 }

 public Student queryStudentById(int id) {
  Student stu;
  try{
   sqlSession = sf.openSession();
   stu = (Student)sqlSession.selectOne("selectStudentById",id);
  }finally{
   sqlSession.close();
  }
  return stu;
 }

 public List<Student> queryStudentsByName(String name) {
  // TODO Auto-generated method stub
  return null;
 }

 public void updateStudent(Student stu) {
  try{
   sqlSession = sf.openSession();
   int returnValue = sqlSession.update("updateStudentById", stu);
   sqlSession.commit();
   System.out.println(returnValue);
  }finally{
   sqlSession.close();
  }
 }


}

猜你喜欢

转载自leon-s-kennedy.iteye.com/blog/1543375