MyBatis從入門到放棄三:一對一關聯查詢,mybatis一對一

來源:互聯網
上載者:User

MyBatis從入門到放棄三:一對一關聯查詢,mybatis一對一
前言

       簡單來說在mybatis.xml中實現關聯查詢實在是有些麻煩,正是因為起架構本質是實現orm的半自動化。 那麼mybatis實現一對一的關聯查詢則是使用association屬性和resultMap屬性。

 

搭建開發環境

      建立student表、teacher表來搭建一對一的關聯查詢情境,student表添加外鍵supervisor_id實現和teacher表的關聯

1 CREATE TABLE [dbo].[t_teacher]( 2 [id] [int] IDENTITY(1,1) NOT NULL, 3 [name] [nvarchar](30) NULL, 4 [title] [nvarchar](30) NULL, 5 PRIMARY KEY CLUSTERED 6 ( 7 [id] ASC 8 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 9 ) ON [PRIMARY]10 11 GOView Code 1 CREATE TABLE [dbo].[t_student]( 2 [id] [int] IDENTITY(1,1) NOT NULL, 3 [name] [nvarchar](30) NULL, 4 [major] [nvarchar](30) NULL, 5 [supervisor_id] [int] NULL, 6 PRIMARY KEY CLUSTERED 7 ( 8 [id] ASC 9 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]10 ) ON [PRIMARY]View Code

 

一對一關聯查詢

   一對一關聯的關鍵是在mapper.xml中建立resultMap。  如下代碼看到了在studentResultMap中添加了屬性association,property是在model類中的外鍵屬性名稱,別忘記指定JavaType

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper 3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <mapper namespace="com.autohome.mapper.Student"> 6     <resultMap id="studentResultMap" type="Student"> 7         <id property="id" column="id"/> 8         <result property="name" column="name"/> 9         <result property="major" column="major"/>10         <association property="supervisor" javaType="Teacher">11             <id property="id" column="t_id" />12             <result property="name" column="t_name"/>13             <result property="title" column="title"/>14         </association>15     </resultMap>16 17  18     <select id="getStudentById" parameterType="int" resultMap="studentResultMap">19         SELECT st.id,st.name,st.major,20                t.id t_id,t.name t_name,t.title21         FROM t_student st inner join t_teacher t on st.supervisor_id=t.id22         where st.id=#{id}23     </select>24 </mapper>

teacher model

public class Teacher {    private int id;    private String name;    private String title;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getTitle() {        return title;    }    public void setTitle(String title) {        this.title = title;    }}

student model

public class Student {    private int id;    private String name;    private String major;    private Teacher supervisor;    public Teacher getSupervisor() {        return supervisor;    }    public void setSupervisor(Teacher supervisor) {        this.supervisor = supervisor;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getMajor() {        return major;    }    public void setMajor(String major) {        this.major = major;    }}

  

單元測試
@Test    public void getStudentById(){        SqlSession sqlSession=null;        try{            sqlSession=sqlSessionFactory.openSession();            Student student = sqlSession.selectOne("com.autohome.mapper.Student.getStudentById",1);            System.out.println("id:"+student.getId()+",name:"+student.getName()+",導師姓名:"+student.getSupervisor().getName()+",導師職稱:"+student.getSupervisor().getTitle());        }catch(Exception e){            e.printStackTrace();        }finally {            sqlSession.close();        }    }

附實現

 

嵌套resultMap

   如上的resultmap用起來總是不方便的,萬一後續再到其他關聯查詢需要用到teacher表呢,那麼我們把teacherResultMap單獨拿出來,不僅是resultMap可以嵌套,sql語句也可以嵌套。

   分別建立studentResultMap和suprvisorResultMap。後在studentResultMap的association中使用resultMap引用supervisorResultMap。

<mapper namespace="com.autohome.mapper.Student">    <resultMap id="studentResultMap" type="Student">        <id property="id" column="id"/>        <result property="name" column="name"/>        <result property="major" column="major"/>        <association property="supervisor" resultMap="suprvisorResultMap"/>    </resultMap>    <resultMap id="suprvisorResultMap" type="Teacher">        <id property="id" column="t_id" />        <result property="name" column="t_name"/>        <result property="title" column="title"/>    </resultMap>    <select id="getStudentById" parameterType="int" resultMap="studentResultMap">        SELECT st.id,st.name,st.major,               t.id t_id,t.name t_name,t.title        FROM t_student st inner join t_teacher t on st.supervisor_id=t.id        where st.id=#{id}    </select></mapper>

實現結果和上面相同

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.