zoukankan      html  css  js  c++  java
  • MyBatis学习之简单增删改查操作、MyBatis存储过程、MyBatis分页、MyBatis一对一、MyBatis一对多

     一、用到的实体类如下:

    Student.java

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


    Group.java

    [java] view plaincopy
     
    1. package com.company.entity;  
    2.   
    3. import java.util.List;  
    4.   
    5. public class Group {  
    6.     private int id;  
    7.     private String name;  
    8.     private String position;  
    9.     private List<Student> students;  
    10.       
    11.       
    12.     public List<Student> getStudents() {  
    13.         return students;  
    14.     }  
    15.     public void setStudents(List<Student> students) {  
    16.         this.students = students;  
    17.     }  
    18.     public int getId() {  
    19.         return id;  
    20.     }  
    21.     public void setId(int id) {  
    22.         this.id = id;  
    23.     }  
    24.     public String getName() {  
    25.         return name;  
    26.     }  
    27.     public void setName(String name) {  
    28.         this.name = name;  
    29.     }  
    30.     public String getPosition() {  
    31.         return position;  
    32.     }  
    33.     public void setPosition(String position) {  
    34.         this.position = position;  
    35.     }  
    36.     @Override  
    37.     public String toString() {  
    38.         return "Group [id=" + id + ", name=" + name + ", position=" + position  
    39.                 + "]";  
    40.     }  
    41.       
    42. }  

    二、实体对应的表结构

    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

    [html] view plaincopy
     
    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.       
    6.     <!-- mybatis缓存 -->  
    7.     <cache eviction="LRU" flushInterval="600000" size="1024" readOnly="false" />  
    8.       
    9.     <!-- sql标签用来定义一些可以被重用的sql语句或字段或片段等 -->  
    10.     <sql id="studentColumns">select id,name,birth from student</sql>  
    11.       
    12.     <!-- 此处获得多对一的关系 ,但就单条记录而言却是一对一的关系,所以一对一的写法跟此相同-->  
    13.     <resultMap type="Student" id="getStudentAndGroup" >  
    14.         <id column="id" property="id"/>  
    15.         <result column="name" property="name"/>  
    16.         <result column="birth" property="birth"/>  
    17.         <association property="group" column="group_id" javaType="Group">  
    18.             <id column="g_id" property="id"/>  
    19.             <result column="g_name" property="name"/>  
    20.             <result column="g_position" property="position"/>  
    21.         </association>  
    22.     </resultMap>  
    23.     <select id="many2one" resultMap="getStudentAndGroup" parameterType="int" >  
    24.         select s.id,s.name,s.birth,s.group_id,g.g_id,g.g_name,g.g_position   
    25.         from student s   
    26.         left join g_group g on s.group_id = g.g_id  
    27.         where s.id = #{id}  
    28.     </select>  
    29.       
    30.       
    31.     <!-- 意图是获得一个学生,并且获得该学生所属的组,跟上面的意思差不多 ,用association的select属性-->  
    32.     <!-- 于上面的相比个人感觉上面的效率要高些,因为上面只有一条sql语句 -->  
    33.     <resultMap type="Student" id="getStudentAndGroupUseSelectMap">  
    34.         <id column="id" property="id"/>  
    35.         <result column="name" property="name"/>  
    36.         <result column="birth" property="birth"/>  
    37.         <association property="group" column="group_id" javaType="Group" select="selectGroup" />  
    38.     </resultMap>  
    39.     <select id="getStudentAndGroupUseSelect" resultMap="getStudentAndGroupUseSelectMap" parameterType="int">  
    40.         select *   
    41.         from student   
    42.         where id = #{id}  
    43.     </select>  
    44.     <select id="selectGroup" resultType="Group" parameterType="int" flushCache="false" useCache="true"><!-- 此处实用缓存 -->  
    45.         select g_id as id, g_name as name, g_position as position   
    46.         from g_group   
    47.         where g_id = #{id}  
    48.     </select>  
    49.   
    50.     <!-- 动态sql语句 的测试dynamic sql-->      
    51.     <select id="getStudentBySomeCondition" parameterType="Student" resultType="Student">  
    52.         select *  
    53.         from student  
    54.         <where>  
    55.             <if test="id != null">  
    56.                 id>2  
    57.             </if>  
    58.             <if test="name != null">  
    59.                 and name like '%g%'  
    60.             </if>  
    61.         </where>  
    62.     </select>  
    63.       
    64.     <!-- MyBatis调用存储过程 -->  
    65.     <resultMap type="Student" id="studentMap">  
    66.         <id column="id" property="id"/>  
    67.         <result column="name" property="name"/>  
    68.         <result column="birth" property="birth"/>  
    69.     </resultMap>  
    70.     <select id="getAllUser" statementType="CALLABLE" >  
    71.         {call get_all_student(#{students ,mode=OUT, jdbcType=CURSOR, javaType=ResultSet, resultMap=studentMap} )}  
    72.     </select>  
    73.       
    74.       
    75.     <!-- MyBatis向student表中插入一条数据 -->  
    76.     <insert id="add" parameterType="Student" keyColumn="id">  
    77.         <selectKey keyProperty="id" order="BEFORE" resultType="int">   
    78.             select stu_id_sequence.nextval from dual  
    79.         </selectKey>  
    80.         insert into student(id,name,birth) values(#{id},#{name},#{birth})  
    81.     </insert>  
    82.       
    83.     <!-- 根据id获得学生的信息 -->  
    84.     <select id="getById" parameterType="int" resultType="Student">  
    85.         <include refid="studentColumns"/> where id=#{id}  
    86.     </select>  
    87.       
    88.     <!-- 此处的实现方法是一个分页的原型,请查看IStudentDAOImpl.java中的调用方法 -->  
    89.     <select id="getAllStudent" resultMap="studentMap">  
    90.         <include refid="studentColumns"/> order by id<!--此处是引用了上面预定义好的sql语句-->  
    91.     </select>  
    92.       
    93.       
    94. </mapper>  


    group.xml

    [html] view plaincopy
     
    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.IGroupDAO">  
    5.       
    6.       
    7.       
    8.     <resultMap type="Group" id="groupResultMap" >  
    9.         <id column="g_id" property="id"/>  
    10.         <result column="g_name" property="name"/>  
    11.         <result column="g_position" property="position"/>  
    12.     </resultMap>  
    13.     <sql id="getALl">select * from</sql>  
    14.       
    15.     <!-- 意图想通过获得组和组中的所有student,此处相当于one2many -->  
    16.     <resultMap type="Group" id="getGroupAndStudents">  
    17.         <id column="g_id" property="id"/>  
    18.         <result column="g_name" property="name"/>  
    19.         <result column="g_position" property="position"/>  
    20.         <collection property="students" ofType="Student" column="group_id"><!-- 注意此处的group_id是student表的外键 -->  
    21.             <id column="id" property="id"/>  
    22.             <result column="name" property="name"/>  
    23.             <result column="birth" property="birth"/>  
    24.         </collection>  
    25.     </resultMap>  
    26.       
    27.       
    28.       
    29.       
    30.       
    31.       
    32.     <select id="getById" parameterType="int" resultMap="getGroupAndStudents">  
    33.         select g.g_id,g.g_name,g.g_position,s.id,s.name,s.birth ,s.group_id  
    34.         from g_group g  
    35.         left join student s on g.g_id = s.group_id  
    36.         where g.g_id = #{id}  
    37.     </select>  
    38.       
    39.     <!--   
    40.     <select id="getById" parameterType="int" resultType="Group">  
    41.         select g_id as id, g_name as name, g_position as position from g_group where g_id=#{id}  
    42.     </select>  
    43.      -->  
    44.     <select id="getByIdResultMap" parameterType="_int" resultMap="groupResultMap">  
    45.         select g_id ,g_name, g_position  from g_group where g_id=#{id}  
    46.     </select>  
    47.     <delete id="deleteById" parameterType="_int" timeout="1000">  
    48.         delete from g_group where g_id=#{id}  
    49.     </delete>  
    50.     <insert id="add" parameterType="Group">  
    51.         insert into g_group(g_id, g_name, g_position)   
    52.         values(#{id}, #{name}, #{position})  
    53.     </insert>  
    54.       
    55. </mapper>  


     

    四、接口IStudentDAO.java和IGroupDAO.java中定义了IStudentDAOImpl.java和IGroupDAOImpl.java中需要实现的方法

    IStudentDAO.java

    [java] view plaincopy
     
    1. package com.company.dao;  
    2.   
    3. import java.util.List;  
    4.   
    5. import com.company.entity.Student;  
    6.   
    7. public interface IStudentDAO {  
    8.     /** 
    9.      * 增加一个学生 
    10.      * @param student 
    11.      */  
    12.     public void add(Student student);  
    13.       
    14.     /** 
    15.      * 根据学生的Id删除学生 
    16.      * @param id 
    17.      */  
    18.     public void deleteById(int id);  
    19.       
    20.     /** 
    21.      * 通过学生的id获得学生的信息 
    22.      * @param id 
    23.      * @return 
    24.      */  
    25.     public Student getById(int id);  
    26.       
    27.     /** 
    28.      * 更新学生信息 
    29.      * @param student 
    30.      */  
    31.     public void update(Student student);  
    32.       
    33.     /** 
    34.      * 此处是MyBatis的分页查询 
    35.      * @return 
    36.      */  
    37.     public List<Student> getAllStudent();  
    38.       
    39.     /** 
    40.      * 多对一 
    41.      * @param id 
    42.      * @return 
    43.      */  
    44.     public Student many2one(int id);  
    45.       
    46.     /** 
    47.      * 获得学生的信息,并且获得该学生所属的组的信息 
    48.      * @param id 
    49.      * @return 
    50.      */  
    51.     public Student getStudentAndGroupUseSelect(int id);  
    52.       
    53.     /** 
    54.      * 动态sql 
    55.      * @param student 
    56.      * @return 
    57.      */  
    58.     public List<Student> getStudentBySomeCondition(Student student);  
    59.       
    60.     /** 
    61.      * 获得所有的学生信息,此处是调用在数据库中存储过程 
    62.      * @return 
    63.      */  
    64.     public List<Student> getAllUser();  
    65. }  


    对应的实现类IStudentDAOImpl.java如下:

    [java] view plaincopy
     
    1. package com.company.dao.impl;  
    2.   
    3. import java.util.ArrayList;  
    4. import java.util.HashMap;  
    5. import java.util.List;  
    6. import java.util.Map;  
    7.   
    8. import org.apache.ibatis.session.RowBounds;  
    9. import org.apache.ibatis.session.SqlSession;  
    10. import org.apache.ibatis.session.SqlSessionFactory;  
    11.   
    12. import com.company.dao.IStudentDAO;  
    13. import com.company.entity.Student;  
    14. import com.company.util.DBUtil;  
    15.   
    16. public class IStudentDAOImpl implements IStudentDAO {  
    17.       
    18.       
    19.       
    20.     public void add(Student student) {  
    21.         SqlSessionFactory sqlSessionFactory = DBUtil.getSqlSessionFactory();  
    22.         SqlSession session = sqlSessionFactory.openSession();  
    23.         try{  
    24.             IStudentDAO dao = session.getMapper(IStudentDAO.class);  
    25.             dao.add(student);  
    26.             session.commit();  
    27.         }catch(Exception e){  
    28.             e.printStackTrace();  
    29.         }finally{  
    30.             session.close();  
    31.         }  
    32.     }  
    33.   
    34.     public void deleteById(int id) {  
    35.   
    36.     }  
    37.   
    38.     public Student getById(int id) {  
    39.         SqlSessionFactory sqlSessionFactory = DBUtil.getSqlSessionFactory();  
    40.         SqlSession session = sqlSessionFactory.openSession();  
    41.         Student student = null;  
    42.         try{  
    43.             IStudentDAO dao = session.getMapper(IStudentDAO.class);  
    44.             student = dao.getById(id);  
    45.         }catch(Exception e){  
    46.             e.printStackTrace();  
    47.         }finally{  
    48.             session.close();  
    49.         }  
    50.         return student;  
    51.     }  
    52.   
    53.     public void update(Student student) {  
    54.   
    55.     }  
    56.       
    57.       
    58.     public List<Student> getStudentsByGroupId(int groupId) {  
    59.         return null;  
    60.     }  
    61.       
    62.     /** 
    63.      * 测试selectList,分页的原型 
    64.      * @author king 
    65.      * @return students 
    66.      * @serialData 2011-7-29 
    67.      */  
    68.     public List<Student> getAllStudent() {  
    69.         SqlSessionFactory sqlSessionFactory = DBUtil.getSqlSessionFactory();  
    70.         SqlSession session = sqlSessionFactory.openSession();  
    71.         List<Student> students = new ArrayList<Student>();  
    72.         try{  
    73.             RowBounds rb = new RowBounds(1,6);//RowBounds的下标是从0开始,表示第一条记录,此表示从第二条记录开始,取6条记录  
    74.             students = session.selectList("com.company.dao.IStudentDAO.getAllStudent", null, rb);  
    75.         }catch(Exception e){  
    76.             e.printStackTrace();  
    77.         }finally{  
    78.             session.close();  
    79.         }  
    80.         return students;  
    81.     }  
    82.   
    83.     public Student many2one(int id) {  
    84.         SqlSessionFactory sqlSessionFactory = DBUtil.getSqlSessionFactory();  
    85.         SqlSession session = sqlSessionFactory.openSession();  
    86.         Student student = null;  
    87.         try{  
    88.             IStudentDAO dao = session.getMapper(IStudentDAO.class);  
    89.             student = dao.many2one(id);  
    90.         }catch(Exception e){  
    91.             e.printStackTrace();  
    92.         }finally{  
    93.             session.close();  
    94.         }  
    95.         return student;  
    96.           
    97.     }  
    98.       
    99.     public Student getStudentAndGroupUseSelect(int id){  
    100.         SqlSessionFactory sqlSessionFactory = DBUtil.getSqlSessionFactory();  
    101.         SqlSession session = sqlSessionFactory.openSession();  
    102.         Student student = null;  
    103.         try{  
    104.             IStudentDAO dao = session.getMapper(IStudentDAO.class);  
    105.             student = dao.getStudentAndGroupUseSelect(id);  
    106.         }catch(Exception e){  
    107.             e.printStackTrace();  
    108.         }finally{  
    109.             session.close();  
    110.         }  
    111.         return student;  
    112.     }  
    113.       
    114.     public List<Student> getStudentBySomeCondition(Student student){  
    115.         SqlSessionFactory sqlSessionFactory = DBUtil.getSqlSessionFactory();  
    116.         SqlSession session = sqlSessionFactory.openSession();  
    117.         List<Student> students = new ArrayList<Student>();  
    118.         try{  
    119.             IStudentDAO dao = session.getMapper(IStudentDAO.class);  
    120.             students = dao.getStudentBySomeCondition(student);  
    121.         }catch(Exception e){  
    122.             e.printStackTrace();  
    123.         }finally{  
    124.             session.close();  
    125.         }  
    126.         return students;  
    127.     }  
    128.       
    129.     public List<Student> getAllUser(){  
    130.         SqlSessionFactory sqlSessionFactory = DBUtil.getSqlSessionFactory();  
    131.         SqlSession session = sqlSessionFactory.openSession();  
    132.         List<Student> students = new ArrayList<Student>();  
    133.         try{  
    134.             Map<String,List<Student>> map = new HashMap<String,List<Student>>();  
    135.             session.selectOne("com.company.dao.IStudentDAO.getAllUser", map);  
    136.             students =  (List<Student>) map.get("students");  
    137.         }catch(Exception e){  
    138.             e.printStackTrace();  
    139.         }finally{  
    140.             session.close();  
    141.         }  
    142.         return students;  
    143.     }  
    144.       
    145.     public static void main(String[] args) {  
    146.         Student student = new Student();  
    147.         IStudentDAOImpl impl = new IStudentDAOImpl();  
    148.         List<Student> students = impl.getAllStudent();  
    149.         for(Student s : students) {  
    150.             System.out.println(s);  
    151.         }  
    152.     }  
    153. }  


     

    IGroupDAO.java代码如下:

    [java] view plaincopy
     
    1. package com.company.dao;  
    2.   
    3. import com.company.entity.Group;  
    4.   
    5. public interface IGroupDAO {  
    6.     /** 
    7.      * 增加一个组 
    8.      * @param group 
    9.      */  
    10.     public void add(Group group);  
    11.     /** 
    12.      * 根据id删除组 
    13.      * @param id 
    14.      */  
    15.     public void deleteById(int id);  
    16.       
    17.     /** 
    18.      * 此方法是通过id获得一个组的信息,并且获得该组下面的所有的学生信息 
    19.      * @param id 
    20.      * @return 
    21.      */  
    22.     public Group getById(int id);  
    23.       
    24.       
    25.     /** 
    26.      * 此方法是测试如何设定ResultMap的方式来从数据库中获得Group 
    27.      * @param id 
    28.      * @return 
    29.      */  
    30.     public Group getByIdResultMap(int id);  
    31.       
    32.       
    33.     public void update(Group group);  
    34.       
    35.       
    36.       
    37. }  


    IGroupDAO.java对应的实现类IGroupDAOImpl.java如下 :

    [java] view plaincopy
     
    1. package com.company.dao.impl;  
    2.   
    3. import org.apache.ibatis.session.SqlSession;  
    4. import org.apache.ibatis.session.SqlSessionFactory;  
    5.   
    6. import com.company.dao.IGroupDAO;  
    7. import com.company.entity.Group;  
    8. import com.company.entity.Student;  
    9. import com.company.util.DBUtil;  
    10.   
    11. public class IGroupDAOImpl implements IGroupDAO{  
    12.   
    13.     public void add(Group group) {  
    14.         SqlSession session = DBUtil.getSqlSessionFactory().openSession();  
    15.         try{  
    16.             IGroupDAO dao = session.getMapper(IGroupDAO.class);  
    17.             dao.add(group);  
    18.             session.commit();  
    19.         }catch(Exception e){  
    20.             e.printStackTrace();  
    21.         }finally{  
    22.             session.close();  
    23.         }  
    24.     }  
    25.       
    26.     public void deleteById(int id) {  
    27.         SqlSession session = DBUtil.getSqlSessionFactory().openSession();  
    28.         try{  
    29.             IGroupDAO dao = session.getMapper(IGroupDAO.class);  
    30.             dao.deleteById(id);  
    31.             session.commit();  
    32.         }catch(Exception e){  
    33.             e.printStackTrace();  
    34.         }finally{  
    35.             session.close();  
    36.         }  
    37.           
    38.     }  
    39.   
    40.     public Group getById(int id) {  
    41.         SqlSessionFactory sqlSessionFactory = DBUtil.getSqlSessionFactory();  
    42.         SqlSession session = sqlSessionFactory.openSession();  
    43.           
    44.         Group group = null;  
    45.         try{  
    46.             IGroupDAO dao = session.getMapper(IGroupDAO.class);  
    47.             group = dao.getById(id);  
    48.         }catch(Exception e){  
    49.             e.printStackTrace();  
    50.         }finally{  
    51.             session.close();  
    52.         }  
    53.         return group;  
    54.     }  
    55.   
    56.     public Group getByIdResultMap(int id) {  
    57.         SqlSessionFactory sqlSessionFactory = DBUtil.getSqlSessionFactory();  
    58.         SqlSession session = sqlSessionFactory.openSession();  
    59.         Group group = null;  
    60.         try{  
    61.             IGroupDAO dao = session.getMapper(IGroupDAO.class);  
    62.             group = dao.getByIdResultMap(id);  
    63.         }catch(Exception e){  
    64.             e.printStackTrace();  
    65.         }finally{  
    66.             session.close();  
    67.         }  
    68.         return group;  
    69.     }  
    70.       
    71.     public void update(Group group) {  
    72.         // TODO Auto-generated method stub  
    73.           
    74.     }  
    75.   
    76.       
    77.     public static void main(String[] args) {  
    78.         //System.out.println(new IGroupDAOImpl().getByIdResultMap(1));  
    79.           
    80.         /*Group group = new Group(); 
    81.         group.setId(3); 
    82.         group.setName("南京农业2"); 
    83.         group.setPosition("南京信新街口2"); 
    84.         new IGroupDAOImpl().add(group);*/  
    85.           
    86.         Group group = new IGroupDAOImpl().getById(1);  
    87.           
    88.         for(Student s:group.getStudents()){  
    89.             System.out.println(s.getId()+" , " + s.getName());  
    90.         }  
    91.           
    92.     }  
    93. }  


    至此,对于一个初学者来说,需要了解的知识,上面的内容都有所概括,关键是灵活的应用。看的时候注意结合,如Student.xml       ,然后IStudentDAO.java, 最后看实现IStudentDAOImpl.java   

  • 相关阅读:
    javascript 解析json数据
    解析 对象列表的JSON数据 []、[{}] 中括号
    # 指针
    # 栈内存和堆内存
    # Linux学习笔记
    # jsp及servlet学习笔记
    # Git学习笔记
    # Excel批量处理数据
    # 数学建模算法
    # VsCode 配置C++调试运行
  • 原文地址:https://www.cnblogs.com/u0mo5/p/4162375.html
Copyright © 2011-2022 走看看