天天看點

MyBatis學習之簡單增删改查操作、MyBatis存儲過程、MyBatis分頁、MyBatis一對一、MyBatis一對多

 一、用到的實體類如下:

Student.java

[html] 

view plain copy

  1. package com.company.entity;  
  2. import java.io.Serializable;  
  3. import java.util.Date;  
  4. public class Student implements Serializable{  
  5.     private static final long serialVersionUID = 1L;  
  6.     private int id;  
  7.     private String name;  
  8.     private Date birth;  
  9.     private Group group;  
  10.     public Group getGroup() {  
  11.         return group;  
  12.     }  
  13.     public void setGroup(Group group) {  
  14.         this.group = group;  
  15.     public int getId() {  
  16.         return id;  
  17.     public void setId(int id) {  
  18.         this.id = id;  
  19.     public String getName() {  
  20.         return name;  
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     public Date getBirth() {  
  24.         return birth;  
  25.     public void setBirth(Date birth) {  
  26.         this.birth = birth;  
  27.     @Override  
  28.     public String toString() {  
  29.         return "Student [birth=" + birth + ", group=" + group + ", id=" + id  
  30.                 + ", name=" + name + "]";  
  31. }  

Group.java

[java] 

  1. import java.util.List;  
  2. public class Group {  
  3.     private String position;  
  4.     private List<Student> students;  
  5.     public List<Student> getStudents() {  
  6.         return students;  
  7.     public void setStudents(List<Student> students) {  
  8.         this.students = students;  
  9.     public String getPosition() {  
  10.         return position;  
  11.     public void setPosition(String position) {  
  12.         this.position = position;  
  13.         return "Group [id=" + id + ", name=" + name + ", position=" + position  
  14.                 + "]";  

二、實體對應的表結構

student表:

create table student(

id  int primary key,

name varchar2(20),

birth date,

group_id int references g_group(g_id));

g_group表:

create  table g_group(

g_id int primary key,

g_name varchar2(20),

g_position varchar2(30));

sequence:

create sequence student_id_sequence;

create sequence group_id_sequence;

三、Student和Group的映射檔案如下,你可以在映射檔案中找到,關于MyBatis的增删改查操作,MyBatis調用存儲過程,MyBatis分頁以及MyBatis對一對一、多對多的處理

xml檔案中都标有注釋,看的時候配合下面的具體實作看,雖然有點亂

student.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4. <mapper namespace="com.company.dao.IStudentDAO">  
  5.     <!-- mybatis緩存 -->  
  6.     <cache eviction="LRU" flushInterval="600000" size="1024" readOnly="false" />  
  7.     <!-- sql标簽用來定義一些可以被重用的sql語句或字段或片段等 -->  
  8.     <sql id="studentColumns">select id,name,birth from student</sql>  
  9.     <!-- 此處獲得多對一的關系 ,但就單條記錄而言卻是一對一的關系,是以一對一的寫法跟此相同-->  
  10.     <resultMap type="Student" id="getStudentAndGroup" >  
  11.         <id column="id" property="id"/>  
  12.         <result column="name" property="name"/>  
  13.         <result column="birth" property="birth"/>  
  14.         <association property="group" column="group_id" javaType="Group">  
  15.             <id column="g_id" property="id"/>  
  16.             <result column="g_name" property="name"/>  
  17.             <result column="g_position" property="position"/>  
  18.         </association>  
  19.     </resultMap>  
  20.     <select id="many2one" resultMap="getStudentAndGroup" parameterType="int" >  
  21.         select s.id,s.name,s.birth,s.group_id,g.g_id,g.g_name,g.g_position   
  22.         from student s   
  23.         left join g_group g on s.group_id = g.g_id  
  24.         where s.id = #{id}  
  25.     </select>  
  26.     <!-- 意圖是獲得一個學生,并且獲得該學生所屬的組,跟上面的意思差不多 ,用association的select屬性-->  
  27.     <!-- 于上面的相比個人感覺上面的效率要高些,因為上面隻有一條sql語句 -->  
  28.     <resultMap type="Student" id="getStudentAndGroupUseSelectMap">  
  29.         <association property="group" column="group_id" javaType="Group" select="selectGroup" />  
  30.     <select id="getStudentAndGroupUseSelect" resultMap="getStudentAndGroupUseSelectMap" parameterType="int">  
  31.         select *   
  32.         from student   
  33.         where id = #{id}  
  34.     <select id="selectGroup" resultType="Group" parameterType="int" flushCache="false" useCache="true"><!-- 此處實用緩存 -->  
  35.         select g_id as id, g_name as name, g_position as position   
  36.         from g_group   
  37.         where g_id = #{id}  
  38.     <!-- 動态sql語句 的測試dynamic sql-->      
  39.     <select id="getStudentBySomeCondition" parameterType="Student" resultType="Student">  
  40.         select *  
  41.         from student  
  42.         <where>  
  43.             <if test="id != null">  
  44.                 id>2  
  45.             </if>  
  46.             <if test="name != null">  
  47.                 and name like '%g%'  
  48.         </where>  
  49.     <!-- MyBatis調用存儲過程 -->  
  50.     <resultMap type="Student" id="studentMap">  
  51.     <select id="getAllUser" statementType="CALLABLE" >  
  52.         {call get_all_student(#{students ,mode=OUT, jdbcType=CURSOR, javaType=ResultSet, resultMap=studentMap} )}  
  53.     <!-- MyBatis向student表中插入一條資料 -->  
  54.     <insert id="add" parameterType="Student" keyColumn="id">  
  55.         <selectKey keyProperty="id" order="BEFORE" resultType="int">   
  56.             select stu_id_sequence.nextval from dual  
  57.         </selectKey>  
  58.         insert into student(id,name,birth) values(#{id},#{name},#{birth})  
  59.     </insert>  
  60.     <!-- 根據id獲得學生的資訊 -->  
  61.     <select id="getById" parameterType="int" resultType="Student">  
  62.         <include refid="studentColumns"/> where id=#{id}  
  63.     <!-- 此處的實作方法是一個分頁的原型,請檢視IStudentDAOImpl.java中的調用方法 -->  
  64.     <select id="getAllStudent" resultMap="studentMap">  
  65.         <include refid="studentColumns"/> order by id<!--此處是引用了上面預定義好的sql語句-->  
  66. </mapper>  

group.xml

  1. <mapper namespace="com.company.dao.IGroupDAO">  
  2.     <resultMap type="Group" id="groupResultMap" >  
  3.         <id column="g_id" property="id"/>  
  4.         <result column="g_name" property="name"/>  
  5.         <result column="g_position" property="position"/>  
  6.     <sql id="getALl">select * from</sql>  
  7.     <!-- 意圖想通過獲得組群組中的所有student,此處相當于one2many -->  
  8.     <resultMap type="Group" id="getGroupAndStudents">  
  9.         <collection property="students" ofType="Student" column="group_id"><!-- 注意此處的group_id是student表的外鍵 -->  
  10.             <id column="id" property="id"/>  
  11.             <result column="name" property="name"/>  
  12.             <result column="birth" property="birth"/>  
  13.         </collection>  
  14.     <select id="getById" parameterType="int" resultMap="getGroupAndStudents">  
  15.         select g.g_id,g.g_name,g.g_position,s.id,s.name,s.birth ,s.group_id  
  16.         from g_group g  
  17.         left join student s on g.g_id = s.group_id  
  18.         where g.g_id = #{id}  
  19.     <!--   
  20.     <select id="getById" parameterType="int" resultType="Group">  
  21.         select g_id as id, g_name as name, g_position as position from g_group where g_id=#{id}  
  22.      -->  
  23.     <select id="getByIdResultMap" parameterType="_int" resultMap="groupResultMap">  
  24.         select g_id ,g_name, g_position  from g_group where g_id=#{id}  
  25.     <delete id="deleteById" parameterType="_int" timeout="1000">  
  26.         delete from g_group where g_id=#{id}  
  27.     </delete>  
  28.     <insert id="add" parameterType="Group">  
  29.         insert into g_group(g_id, g_name, g_position)   
  30.         values(#{id}, #{name}, #{position})  

四、接口IStudentDAO.java和IGroupDAO.java中定義了IStudentDAOImpl.java和IGroupDAOImpl.java中需要實作的方法

IStudentDAO.java

  1. package com.company.dao;  
  2. import com.company.entity.Student;  
  3. public interface IStudentDAO {  
  4.     /** 
  5.      * 增加一個學生 
  6.      * @param student 
  7.      */  
  8.     public void add(Student student);  
  9.      * 根據學生的Id删除學生 
  10.      * @param id 
  11.     public void deleteById(int id);  
  12.      * 通過學生的id獲得學生的資訊 
  13.      * @return 
  14.     public Student getById(int id);  
  15.      * 更新學生資訊 
  16.     public void update(Student student);  
  17.      * 此處是MyBatis的分頁查詢 
  18.     public List<Student> getAllStudent();  
  19.      * 多對一 
  20.     public Student many2one(int id);  
  21.      * 獲得學生的資訊,并且獲得該學生所屬的組的資訊 
  22.     public Student getStudentAndGroupUseSelect(int id);  
  23.      * 動态sql 
  24.     public List<Student> getStudentBySomeCondition(Student student);  
  25.      * 獲得所有的學生資訊,此處是調用在資料庫中存儲過程 
  26.     public List<Student> getAllUser();  

對應的實作類IStudentDAOImpl.java如下:

  1. package com.company.dao.impl;  
  2. import java.util.ArrayList;  
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5. import org.apache.ibatis.session.RowBounds;  
  6. import org.apache.ibatis.session.SqlSession;  
  7. import org.apache.ibatis.session.SqlSessionFactory;  
  8. import com.company.dao.IStudentDAO;  
  9. import com.company.util.DBUtil;  
  10. public class IStudentDAOImpl implements IStudentDAO {  
  11.     public void add(Student student) {  
  12.         SqlSessionFactory sqlSessionFactory = DBUtil.getSqlSessionFactory();  
  13.         SqlSession session = sqlSessionFactory.openSession();  
  14.         try{  
  15.             IStudentDAO dao = session.getMapper(IStudentDAO.class);  
  16.             dao.add(student);  
  17.             session.commit();  
  18.         }catch(Exception e){  
  19.             e.printStackTrace();  
  20.         }finally{  
  21.             session.close();  
  22.         }  
  23.     public void deleteById(int id) {  
  24.     public Student getById(int id) {  
  25.         Student student = null;  
  26.             student = dao.getById(id);  
  27.         return student;  
  28.     public void update(Student student) {  
  29.     public List<Student> getStudentsByGroupId(int groupId) {  
  30.         return null;  
  31.      * 測試selectList,分頁的原型 
  32.      * @author king 
  33.      * @return students 
  34.      * @serialData 2011-7-29 
  35.     public List<Student> getAllStudent() {  
  36.         List<Student> students = new ArrayList<Student>();  
  37.             RowBounds rb = new RowBounds(1,6);//RowBounds的下标是從0開始,表示第一條記錄,此表示從第二條記錄開始,取6條記錄  
  38.             students = session.selectList("com.company.dao.IStudentDAO.getAllStudent", null, rb);  
  39.     public Student many2one(int id) {  
  40.             student = dao.many2one(id);  
  41.     public Student getStudentAndGroupUseSelect(int id){  
  42.             student = dao.getStudentAndGroupUseSelect(id);  
  43.     public List<Student> getStudentBySomeCondition(Student student){  
  44.             students = dao.getStudentBySomeCondition(student);  
  45.     public List<Student> getAllUser(){  
  46.             Map<String,List<Student>> map = new HashMap<String,List<Student>>();  
  47.             session.selectOne("com.company.dao.IStudentDAO.getAllUser", map);  
  48.             students =  (List<Student>) map.get("students");  
  49.     public static void main(String[] args) {  
  50.         Student student = new Student();  
  51.         IStudentDAOImpl impl = new IStudentDAOImpl();  
  52.         List<Student> students = impl.getAllStudent();  
  53.         for(Student s : students) {  
  54.             System.out.println(s);  

IGroupDAO.java代碼如下:

  1. import com.company.entity.Group;  
  2. public interface IGroupDAO {  
  3.      * 增加一個組 
  4.      * @param group 
  5.     public void add(Group group);  
  6.      * 根據id删除組 
  7.      * 此方法是通過id獲得一個組的資訊,并且獲得該組下面的所有的學生資訊 
  8.     public Group getById(int id);  
  9.      * 此方法是測試如何設定ResultMap的方式來從資料庫中獲得Group 
  10.     public Group getByIdResultMap(int id);  
  11.     public void update(Group group);  

IGroupDAO.java對應的實作類IGroupDAOImpl.java如下 :

  1. import com.company.dao.IGroupDAO;  
  2. public class IGroupDAOImpl implements IGroupDAO{  
  3.     public void add(Group group) {  
  4.         SqlSession session = DBUtil.getSqlSessionFactory().openSession();  
  5.             IGroupDAO dao = session.getMapper(IGroupDAO.class);  
  6.             dao.add(group);  
  7.             dao.deleteById(id);  
  8.     public Group getById(int id) {  
  9.         Group group = null;  
  10.             group = dao.getById(id);  
  11.     public Group getByIdResultMap(int id) {  
  12.             group = dao.getByIdResultMap(id);  
  13.     public void update(Group group) {  
  14.         // TODO Auto-generated method stub  
  15.         //System.out.println(new IGroupDAOImpl().getByIdResultMap(1));  
  16.         /*Group group = new Group(); 
  17.         group.setId(3); 
  18.         group.setName("南京農業2"); 
  19.         group.setPosition("南京信新街口2"); 
  20.         new IGroupDAOImpl().add(group);*/  
  21.         Group group = new IGroupDAOImpl().getById(1);  
  22.         for(Student s:group.getStudents()){  
  23.             System.out.println(s.getId()+" , " + s.getName());  

至此,對于一個初學者來說,需要了解的知識,上面的内容都有所概括,關鍵是靈活的應用。看的時候注意結合,如Student.xml       ,然後IStudentDAO.java, 最後看實作IStudentDAOImpl.java