mybatis-映射器-resultMap结果集映射2-association一对一级联

来源:互联网 发布:ug安装java虚拟机 编辑:程序博客网 时间:2024/06/05 09:09

       在实际操作中,我们需要确定对象的关系。这里以前面的学生信息级联为例,在学校里面学生Student和学生证StudentCard是一对一的关系,前面已经建立了Student和StudentCard的pojo对象。那么在Student的pojo添加一个属性studentCard,那么这样就建立了一对一的级联了。现在Student类的代码如下:

   

package org.mybatis.pojo;/** *  * 学生类 *  * @author wj * */public class Student {private int id;// 学生编号private String name;// 学生姓名private byte sex;// 性别private int cardNo;// 学生证号private String note;// 备注private StudentCard studentCard;// 学生证对象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 byte getSex() {return sex;}public void setSex(byte sex) {this.sex = sex;}public int getCardNo() {return cardNo;}public void setCardNo(int cardNo) {this.cardNo = cardNo;}public String getNote() {return note;}public void setNote(String note) {this.note = note;}public StudentCard getStudentCard() {return studentCard;}public void setStudentCard(StudentCard studentCard) {this.studentCard = studentCard;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", cardNo=" + cardNo + ", note=" + note+ ", studentCard=" + studentCard + "]";}}



     这时候我们需要建立Student的映射器StudentMapper和学生证的映射器StudentCardMapper。而在StudentCardMapper里面我们提供一个findStudentCardByStudentId的方法,代码如下:

<?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="org.mybatis.mapper.StudentCardMapper"><resultMap type="org.mybatis.pojo.StudentCard" id="studentCardMap"><id property="id" column="id"/><result property="studentId" column="student_id"/><result property="nativePlace" column="native_place"/><result property="issueDate" column="issue_date"/><result property="endDate" column="end_date"/><result property="note" column="note" /></resultMap><select id="findStudentCardByStudentId" parameterType="int"resultMap="studentCardMap">select id,student_id,native_place,issue_date,end_date,note fromt_student_card where student_id =#{studentId}</select></mapper>


     有了以上的代码,我们将可以在StudentMapper里面使用StudentCardMapper进行级联,代码如下:

<?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="org.mybatis.mapper.StudentMapper"><resultMap type="org.mybatis.pojo.Student" id="studentMap"><id property="id" column="id" /><result property="name" column="name" /><result property="sex" column="sex" /><result property="cardNo" column="card_no" /><result property="note" column="note" /><association property="studentCard" column="id"select="org.mybatis.mapper.StudentCardMapper.findStudentCardByStudentId" /></resultMap><select id="getStudent" parameterType="int" resultMap="studentMap">select id,name,sex,card_no,note from t_student where id = #{id}</select></mapper>


     注意看:<association property="studentCard" column="id"
select="org.mybatis.mapper.StudentCardMapper.findStudentCardByStudentId" />

    这是通过一次关联来处理问题,其中select元素由指定的sql去查询,而column则是指定传递给select语句的参数,这里是Student对象的id。其中参数是Student的id值,通过column配置,如果是多个参数,则使用逗号分隔当取出Student的时候,mybatis就会知道用下面的sql取出我们需要的级联信息:

org.mybatis.mapper.StudentCardMapper.findStudentCardByStudentId

     其中参数是Student的id值,通过column配置,如果是多个参数,则使用逗号分隔。

     创建StudentMapper接口代码如下:

    

package org.mybatis.mapper;import org.mybatis.pojo.Student;/** *  * @author wj 学生mapper */public interface StudentMapper {// 根据学生id获取指定的学生对象public Student getStudent(int studentId);}

    创建StudentCardMapper接口代码如下:

  

package org.mybatis.mapper;import org.mybatis.pojo.StudentCard;/** *  * @author wj 学生证mapper */public interface StudentCardMapper {// 通过学生id查找学生证public StudentCard findStudentCardByStudentId();}


     把StudentMapper.xml和StudentCardMapper.xml添加到mybatis的配置文件中,完整代码如下:

<?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><properties resource="org/mybatis/config/database.properties" /><settings><setting name="logImpl" value="LOG4J" /></settings><!-- 定义类的别名 --><typeAliases><typeAlias type="org.mybatis.pojo.Role" alias="role" /></typeAliases><!-- 定义数据库信息,默认使用development数据库构建环境 --><environments default="development"><environment id="development"><!--采用jdbc事务管理 --><transactionManager type="JDBC"><property name="autoCommit" value="false" /></transactionManager><!-- 配置数据库连接信息 --><dataSource type="POOLED"><property name="driver" value="${driver}" /><property name="url" value="${url}" /><property name="username" value="${username}" /><property name="password" value="${password}" /></dataSource></environment></environments><mappers><mapper resource="org/mybatis/mapper/RoleMapper.xml" /><mapper resource="org/mybatis/mapper/userMapper.xml" /><mapper resource="org/mybatis/mapper/StudentMapper.xml" /><mapper resource="org/mybatis/mapper/StudentCardMapper.xml" /></mappers></configuration>


     给数据库添加测试数据:

   INSERT INTO `t_student` VALUES ('1', 'jack1', '1', '1', 'this student isjack1');

   INSERT INTO `t_student_card` VALUES ('1', '1', '湖南', '2017-06-13', '2017-07-22', 'this is card,the id is 1');

  

  下面是测试代码,如下:

  

package org.mybatis.test;import org.apache.ibatis.session.SqlSession;import org.mybatis.mapper.StudentMapper;import org.mybatis.pojo.Student;import org.mybatis.util.SqlSessionFactoryUtil;public class MybatisMainTest5 {public static void main(String[] args) {// TODO Auto-generated method stubSqlSession sqlSession = null;try {sqlSession = SqlSessionFactoryUtil.openSqlSession();StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);Student student = studentMapper.getStudent(1);System.out.println("the student is : " + student);} catch (Exception e) {System.err.println(e.getMessage());sqlSession.rollback();} finally {if (sqlSession != null) {sqlSession.close();}}}}

      运行程序,下面是打印的日志:

DEBUG  2017-06-13 23:30:08,388  org.apache.ibatis.datasource.pooled.PooledDataSource:  Created connection 1627821297.DEBUG  2017-06-13 23:30:08,389  org.apache.ibatis.transaction.jdbc.JdbcTransaction:  Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@610694f1]DEBUG  2017-06-13 23:30:08,391  org.apache.ibatis.logging.jdbc.BaseJdbcLogger:  ==>  Preparing: select id,name,sex,card_no,note from t_student where id = ? DEBUG  2017-06-13 23:30:08,429  org.apache.ibatis.logging.jdbc.BaseJdbcLogger:  ==> Parameters: 1(Integer)DEBUG  2017-06-13 23:30:08,449  org.apache.ibatis.logging.jdbc.BaseJdbcLogger:  ====>  Preparing: select id,student_id,native_place,issue_date,end_date,note from t_student_card where student_id =? DEBUG  2017-06-13 23:30:08,449  org.apache.ibatis.logging.jdbc.BaseJdbcLogger:  ====> Parameters: 1(Integer)DEBUG  2017-06-13 23:30:08,455  org.apache.ibatis.logging.jdbc.BaseJdbcLogger:  <====      Total: 1DEBUG  2017-06-13 23:30:08,456  org.apache.ibatis.logging.jdbc.BaseJdbcLogger:  <==      Total: 1the student is : Student [id=1, name=jack1, sex=1, cardNo=1, note=this student isjack1, studentCard=StudentCard [id=1, studentId=1, nativePlace=湖南, issueDate=Tue Jun 13 00:00:00 CST 2017, endDate=Sat Jul 22 00:00:00 CST 2017, note=this is card,the id is 1]]DEBUG  2017-06-13 23:30:08,457  org.apache.ibatis.transaction.jdbc.JdbcTransaction:  Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@610694f1]DEBUG  2017-06-13 23:30:08,458  org.apache.ibatis.transaction.jdbc.JdbcTransaction:  Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@610694f1]DEBUG  2017-06-13 23:30:08,460  org.apache.ibatis.datasource.pooled.PooledDataSource:  Returned connection 1627821297 to pool.

      通过看日志,我们能够了解整个执行过程,它先查询出Student的信息,然后根据其id查询出学生证的信息,而参数是Student对象的id值。这样当我们查找到Student的时候,便能把其学生证的信息也同时取到,这便是一对一的级联。

    



阅读全文
0 0
原创粉丝点击