zoukankan      html  css  js  c++  java
  • MyBatis(3.2.3)

    We can get Student along with the Address details using a nested Select query as follows:

    <resultMap type="Address" id="AddressResult">
        <id property="addrId" column="addr_id"/>
        <result property="street" column="street"/>
        <result property="city" column="city"/>
        <result property="state" column="state"/>
        <result property="zip" column="zip"/>
        <result property="country" column="country"/>
    </resultMap>
    <select id="findAddressById" parameterType="int" resultMap="AddressResult">
        SELECT * FROM ADDRESSES WHERE ADDR_ID = #{id}
    </select>
    
    <resultMap type="Student" id="StudentWithAddressResult">
        <id property="studId" column="stud_id"/>
        <result property="name" column="name"/>
        <result property="email" column="email"/>
        <association property="address" column="addr_id" select="findAddressById"/>
    </resultMap>
    <select id="findStudentWithAddress" parameterType="int" resultMap="StudentWithAddressResult">
        SELECT * FROM STUDENTS WHERE STUD_ID = #{Id}
    </select>

    In this approach, the <association> element's select attribute is set to the statement id findAddressById. Here, two separate SQL statements will be executed against the database, the first one called findStudentById to load student details and the second one called findAddressById to load its address details.

    The addr_id column value will be passed as input to the selectAddressById statement.

    We can invoke the findStudentWithAddress mapped statement as follows:

    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    Student student = mapper.selectStudentWithAddress(studId);
    System.out.println(student);
    System.out.println(student.getAddress());
  • 相关阅读:
    聚集索引
    第一天 尝试Thread
    sql 分区函数
    sql 查询表定义
    千万数量级分页存储过程
    成语解释
    sql 分组查询满足条件所以数据
    sql存储过程
    联表更新的反思
    从表保存了主表的id,以分号分隔,怎么样用一条sql搞定主表满足条件的查询? 不希望单独写存储过程,或者后台拆成int后传进来,就一条sql 搞定,一条
  • 原文地址:https://www.cnblogs.com/huey/p/5230802.html
Copyright © 2011-2022 走看看