• Mybatis框架中实现双向一对多关系映射


     

    学习过Hibernate框架的伙伴们很容易就能简单的配置各种映射关系(Hibernate框架的映射关系在我的blogs中也有详细的讲解),但是在Mybatis框架中我们又如何去实现

    一对多的关系映射呢? 其实很简单

    主配置文件:Configuration.xml

    复制代码
    <?xml version="1.0" encoding="UTF-8" ?>
    
    <!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <configuration>
      <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC">
            <property name="" value=""/>
          </transactionManager>
          <dataSource type="UNPOOLED">
            <property name="driver" value="oracle.jdbc.OracleDriver"/>
            <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
            <property name="username" value="practice"/>
            <property name="password" value="123"/>
          </dataSource>
        </environment>
      </environments>
      
       <mappers>
        <mapper resource="config/Student.xml"/>
        <mapper resource="config/Grade.xml"/>
      </mappers> 
    
    </configuration>
    复制代码

     

    背景:学生和班级是一个典型的一对多的关系,一个班级可以对应着多个学生,所以我们随即创建了学生对象和班级对象

    学生类:Student

    复制代码
    package entity;
    /*
     * 学生类
     * */
    public class Student {
        //学生编号
        private Integer sid;
        //学生名称
        private String sname;
        //学生性别
        private String sex;
        
        public Student() {
        }
        public Student(String sname, String sex) {
            this.sname = sname;
            this.sex = sex;
        }
        public Integer getSid() {
            return sid;
        }
        public void setSid(Integer sid) {
            this.sid = sid;
        }
        public String getSname() {
            return sname;
        }
        public void setSname(String sname) {
            this.sname = sname;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        
    }
    复制代码

     

    班级类:Grade

    复制代码
    package entity;
    
    import java.util.HashSet;
    import java.util.Set;
    
    /*
     * 班级类
     * */
    public class Grade {
        //班级编号
        private Integer gid;
        //班级名称
        private String gname;
        //班级描述
        private String gdesc;
        //班级下的学生信息
        private Set<Student> stus=new HashSet<Student>();
        
        public Set<Student> getStus() {
            return stus;
        }
        public void setStus(Set<Student> stus) {
            this.stus = stus;
        }
        public Grade() {
        }
        public Grade(Integer gid, String gname, String gdesc) {
            this.gid = gid;
            this.gname = gname;
            this.gdesc = gdesc;
        }
        public Integer getGid() {
            return gid;
        }
        public void setGid(Integer gid) {
            this.gid = gid;
        }
        public String getGname() {
            return gname;
        }
        public void setGname(String gname) {
            this.gname = gname;
        }
        public String getGdesc() {
            return gdesc;
        }
        public void setGdesc(String gdesc) {
            this.gdesc = gdesc;
        }
        
    }
    复制代码

    实体类准备完了的话,我们就可以开始看配置文件了,也是最关键的一部分

    首先讲简单点的学生实体类对应的配置文件

    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="Student">
    
      <resultMap type="entity.Student" id="StudentResult">
        <id column="sid" jdbcType="INTEGER" property="sid"/>
        <result column="sname" jdbcType="VARCHAR" property="sname"/>
        <result column="sex" jdbcType="VARCHAR" property="sex"/>
      </resultMap>
    
    </mapper>
    复制代码

    然后就是最关键的班级实体的配置文件了

    Grade.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="Grade">
    
      <resultMap type="entity.Grade" id="GradeResult">
        <id column="gid" jdbcType="INTEGER" property="gid"/>
        <result column="gname" jdbcType="VARCHAR" property="gname"/>
        <result column="gdesc" jdbcType="VARCHAR" property="gdesc"/>
        <!-- 一对多关系 -->
        <collection property="stus" resultMap="Student.StudentResult"></collection>
      </resultMap>
         
        <!-- 查询所有信息 -->
        <select id="selectAllInfo" resultMap="GradeResult">
            <!-- select sid,sname,sex,g.gid,gname,gdesc from Student s,Grade g where s.gid=g.gid -->
            select sid,sname,sex,g.gid,gname,gdesc from Student s left join Grade g on s.gid=g.gid
        </select>
    </mapper>
    复制代码

    以上就是对配置文件的解释了

    接下来我们就可以进行一道测试了

    复制代码
    /*
         * 1.1 查询所有的班级和班级下的所有学生(一对多)
         * */
        @Test
        public void selectAllStu() throws Exception{
            //通过配置文件获取到数据库连接信息
            Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
            //通过配置信息构建一个SessionFactory工厂
            SqlSessionFactory sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
            //通过SessionFaction打开一个回话通道
            SqlSession session = sqlsessionfactory.openSession();
            /*SqlSession session =MybatisUtil.getSession();*/
            //调用配置文件中的sql语句
            List<Grade> list = session.selectList("Grade.selectAllInfo");
            //遍历查询出来的结果
            for (Grade grade : list) {
                System.out.println("班级:"+grade.getGname());
                for (Student stu : grade.getStus()) {
                    System.out.println("学生:"+stu.getSname());
                }
            }
            
            session.close();
        }
        
    复制代码

     

    执行后,查询出来的结果是

     

    以上是第一种一对多关系映射的方式,下面是第二种一对多映射的方法,其他的所有步骤和上面的都是一样的只有相对应的配置文件不同,所以我就只贴小配置了

    Grade.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="Grade">
    
      <resultMap type="entity.Grade" id="GradeResult">
        <id column="gid" jdbcType="INTEGER" property="gid"/>
        <result column="gname" jdbcType="VARCHAR" property="gname"/>
        <result column="gdesc" jdbcType="VARCHAR" property="gdesc"/>
        <!-- 一对多关系 -->
        <!-- <collection property="stus" resultMap="Student.StudentResult"></collection>  -->
        <collection property="stus" javaType="entity.Student">
            <id property="sid" column="sid"/>
            <result property="sname" column="sname"/>
            <result property="sex" column="sex"/>
        </collection>
      </resultMap>
         
        <!-- 查询所有信息 -->
        <select id="selectAllInfo" resultMap="GradeResult">
            <!-- select sid,sname,sex,g.gid,gname,gdesc from Student s,Grade g where s.gid=g.gid -->
            select sid,sname,sex,g.gid,gname,gdesc from Student s left join Grade g on s.gid=g.gid
        </select>
        
        <!-- 新增班级并同时新增班级下的学生 -->
        <!--useGeneratedKeys=true 表明采用主键生成策略
            keyProperty="gid"  表明将生成的主键添加到parameterType类中的那个属性值中去
          -->
        <!-- <insert id="" useGeneratedKeys="true" keyProperty="gid" parameterType="entity.Grade">
            
        </insert> -->
    </mapper>
    复制代码

     

     

    接下来就可以在多的一方配置一的关联关系了

    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="Student">
    
      <resultMap type="entity.Student" id="StudentResult">
        <id column="sid" jdbcType="INTEGER" property="sid"/>
        <result column="sname" jdbcType="VARCHAR" property="sname"/>
        <result column="sex" jdbcType="VARCHAR" property="sex"/>
        <!-- 多对一 -->
       <!--  <association property="grade" resultMap="Grade.GradeResult"></association> -->
        <association property="grade" javaType="entity.Grade">
            <id property="gid" column="gid"/>
            <result property="gname" column="gname"/>
            <result property="gdesc" column="gdesc"/>
        </association>
      </resultMap>
      
        <!-- 使用别名 -->
        <sql id="cloums">
            s.sid,s.sname,s.sex ,g.gid,g.gname,g.gdesc
        </sql>
        <!-- 多对一查询学生的班级 -->
        <select id="selectGradeByStu" resultMap="StudentResult">
            select <include refid="cloums"/> from Student s ,Grade g where s.gid=g.gid
        </select>
        
        <!-- 简单查询所有信息 -->
         <select id="selectAllStu"  resultMap="StudentResult">
            select sid,sname,sex,gid from Student 
        </select> 
        
        <!--动态拼接Sql  -->
         <select id="selectAllStuByWhere" parameterType="entity.Student"  resultMap="StudentResult">
            select sid,sname,sex,gid from Student where 1=1
            <if test="sname!=null and !&quot;&quot;.equals(sname.trim())">
                <!-- and sname like '%'|| #{sname}|| '%' --> <!-- 模糊查询 -->
                and sname like '%${sname}%'<!-- 模糊查询 -->
                <!-- and sname = #{sname} -->
            </if>
         </select>
         
         <!-- 新增学生信息 -->
         <insert id="InsertStuInfo" parameterType="entity.Student" >
             insert into Student values(SEQ_NUM.Nextval,#{sname},#{sex},1)
         </insert>
         
         <!-- 删除学生信息 -->
         <insert id="DeleteStuBySid" parameterType="int">
             delete from Student where sid=#{sid}
         <!--或者是     delete from Student where sid=#{_parameter} -->
         </insert>
         
         <!-- 根据SID修改学生信息 -->
         <update id="UpdateStuBySid" parameterType="entity.Student" >
             update Student set sname=#{sname},sex=#{sex} where sid=#{sid}
         </update>
         
         
    </mapper>
    复制代码

     

     上述内容摘自http://www.cnblogs.com/liujiayun/p/5814158.html!

     

  • 相关阅读:
    js事件列表
    PS快捷键
    去水印六种方法
    ps素材网站
    颜色搭配
    收集的各大官网的样式初始化
    目前公司用到的PC端和移动端的初始化样式
    CSS背景图拉伸自适应尺寸,全浏览器兼容代码
    队列的优化链式实现
    队列的优化顺序实现
  • 原文地址:https://www.cnblogs.com/wangzheand/p/5818810.html
Copyright © 2020-2023  润新知