• 学习Mybatis中的一对一表关联


    一、使用业务扩张类实现一对一映射,创建表person

    create table person(
    
    id int(11),
    
    name varchar(255),
    
    age int(11),
    
    sex int(11),
    
    cardId int(11),
    
    primary key(id),
    
    foreign key(cardId) references person_card(cardId)
    )
    
    create table person_card(
    
    cardId int(11),
    
    cardInfo varchar(255)
    
    )
    

      然后在项目entity包下创建实体类personBusiness.java

    package org.ruangong.entity;
    
    public class PersonBusiness extends Person{
    	private int cardId;
    	private String cardinfo;
    	public int getCardId() {
    		return cardId;
    	}
    	public void setCardId(int cardId) {
    		this.cardId = cardId;
    	}
    	public String getCardinfo() {
    		return cardinfo;
    	}
    	public void setCardinfo(String cardinfo) {
    		this.cardinfo = cardinfo;
    	}
    	@Override
    	public String toString() {
    		return super.toString()+"PersonBusiness [cardId=" + cardId + ", cardinfo=" + cardinfo + "]";
    	}
    	
    }
    

      通过继承person实体类来实现返回值的要求。

    在personMapper.xml中:

     <select id="queryPerson_cardId" resultType="PersonBusiness" parameterType="int">
    	 	select P.*,C.* from person2 P inner join person_card C on P.cardId = C.cardId
    	 	 where P.id = #{id}
    	 </select>
    

      二、使用resultmap实现一对一表映射,创建实体类PersonCard。

    package org.ruangong.entity;
    
    public class PersonCard {
    	private int cardId;
    	private String cardInfo;
    	public int getCardId() {
    		return cardId;
    	}
    	public String getCardInfo() {
    		return cardInfo;
    	}
    	public void setCardInfo(String cardInfo) {
    		this.cardInfo = cardInfo;
    	}
    	public void setCardId(int cardId) {
    		this.cardId = cardId;
    	}
    	
    }
    

      在实体类Person中添加Private PersonCard card。

    private PersonCard card;
    

      在personMapper.xml中添加:

    <!-- 使用resultMap关联查询 -->
    	   <select id="queryPerson_cardId2" resultMap="person_card_map" parameterType="int">
    	 	select P.*,C.* from person2 P inner join person_card C on P.cardId = C.cardId
    	 	 where P.id = #{id}
    	 </select>
    	  <resultMap type="person" id="person_card_map">
    		  <id property="id" column="id"/>
    		  <result property="name" column="name"/>
    		  <result property="age" column="age"/>
    		  <result property="persex" column="sex"/>
    		  <association property="card" javaType="PersonCard">
    		  	<id property="cardId" column="cardId"/>
    		  	<result property="cardInfo" column="cardInfo"/>
    		  </association>
    	  </resultMap>
    

      即可实现查询,不用创建业务扩展类。

  • 相关阅读:
    POJ 3177 Redundant Paths(无向图缩点)
    POJ 1502 MPI Maelstrom
    LightOJ 1094
    POJ 1564 Sum It Up(深搜)
    C语言复习6_doWhile循环
    进阶学习
    C语言复习5_调试
    C语言复习4_while循环
    C语言复习3_条件结构
    C语言复习2_运算符
  • 原文地址:https://www.cnblogs.com/jccjcc/p/13964364.html
Copyright © 2020-2023  润新知