Mybatis_Association标签三种用法

`father`表

CREATE TABLE `father` (
  `ID` int(11) NOT NULL,
  `NAME` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `father` VALUES ('1', '李靖');
INSERT INTO `father` VALUES ('2', '康熙');

`son`表

CREATE TABLE `son` (
  `ID` int(11) NOT NULL,
  `FATHER_ID` int(11) DEFAULT NULL,
  `NAME` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `son` VALUES ('1', '2', '雍正');
INSERT INTO `son` VALUES ('2', '1', '哪吒');

Father.java

public class Father {
	private Integer id;

	private String name;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name == null ? null : name.trim();
	}
}

Son.java

public class Son {
	private Integer id;

	private Father father;

	private String name;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Father getFather() {
		return father;
	}

	public void setFather(Father father) {
		this.father = father;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name == null ? null : name.trim();
	}
}

FatherMapper.xml




  
  
    
    
  
  
  
    ID, NAME
  
  
  
  

SonMapper.xml





  
    
    
    
  
  
  
    ID, FATHER_ID, NAME
  
  
  
 

association的用法一: 直接在SonMapper.xml中的association标签里写对应的列名, 且列明需要写别名, 例如: father.ID AS F_ID





  
    
    
    
     
      
        
    
  

  
    son.ID, son.NAME, father.ID AS F_ID, father.NAME AS F_NAME
  

  

调用selectByPrimaryKey传入id=2, 查询结果如下

{
	"id": 2,
	"father": {
		"id": 1,
		"name": "李靖"
	},
	"name": "哪吒"
}

association的用法二: association传入一个ResultMap, 改写SonMapper.xml





  
    
    
    
    
  

  
    son.ID, son.NAME, father.ID AS F_ID, father.NAME AS F_NAME
  

  

association 标签中resultMap属性指向FatherMapper.xml中的BaseResultMap, 这种情况下要求father表和son表没有相同名字的字段, 否则会失败. 调用selectByPrimaryKey传入id=2, 查询结果失败如下:

{
	"id": 2,
	"father": {
		"id": 2,
		"name": "哪吒"
	},
	"name": "哪吒"
}

association的用法三: 给association传入一个select, 





  
    
    
    
    
  

  
    ID, NAME, FATHER_ID
  

  

这种方式相当于将原来的

 替换成

改动最小, 需要assonciation标签放到所有result标签之后, select语句还可以延迟加载.

在一个中,属性出现的先后顺序必须是:constructor-->id --> result--> association-->collection -->discriminator

你可能感兴趣的:(mybatis)