- 1、使用场景
当前有个人,这个人有个身份ID,需要你查询这个人的时候,同时也把这个人的身份ID查询出来,如这样
{
"id": 1,
"name_hh": "ll",
"sex": "男",
"age": 23,
"card": {
"id": 1,
"code": "123321456654"
}
}
drop table if EXISTS tb_card;
create table tb_card (
id BIGINT(20) not null auto_increment,
code VARCHAR(20) DEFAULT '',
PRIMARY KEY (id)
) engine=InnoDB default charset=utf8 COMMENT '身份卡';
insert into tb_card (code) VALUES ('1233244444');
insert into tb_card (code) VALUES ('123326666666');
drop table if EXISTS tb_person;
create table tb_person (
id bigint(20) not null auto_increment,
name VARCHAR(10) DEFAULT '',
sex VARCHAR(5) DEFAULT '',
age int(3) DEFAULT 0,
card_id bigint(20) UNIQUE,
PRIMARY key (id),
-- 关联一个外键,用于连表查询
foreign key (card_id) REFERENCES tb_card (id)
) ENGINE = INNODB DEFAULT CHARSET = utf8 COMMENT '人';
insert into tb_person (name,sex,age,card_id) VALUES ('ll', '男', 23, 1);
insert into tb_person (name,sex,age,card_id) VALUES ('jj', '男', 23, 2);
insert into tb_person (name,sex,age,card_id) VALUES ('ww', '男', 23, 3);
@Data
public class Card {
private BigInteger id;
private String code;
}
@Data
public class Person {
private BigInteger id;
private String name_hh;
private String sex;
private Integer age;
// 人和身份证是一对一
// 查询人的时候,这里关联card对象,用于关联查询
private Card card;
}
<?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="com.project.userservice.mapper.RelateMapper">
<select id="getCard" parameterType="string" resultType="card">
select * from tb_card where id = #{id}
</select>
<select id="getPerson" parameterType="string" resultMap="personMap">
select * from tb_person where id = #{id}
</select>
// type 对应result(结果)的对象或者结果
// <result property="name_hh" column="name"></result> 如果数据库字段名和对象属性一一对应,这里可以忽略不写,也可单独写哪些不同的。
// association用于单个对象,管理和person对应的关联的card属性
// property 对应person中的对象字段
// column 对应数据中的person对应card的关联外键
// select 调用查询card信息的方法。这里多了一次查询,而不用外面调用赋值了
<resultMap id="personMap" type="person">
<result property="name_hh" column="name"></result>
<association property="card" column="card_id" javaType="card" select="getCard">
</association>
</resultMap>
</mapper>
@RequestMapping("/per/{id}")
public Person getPerson(@PathVariable("id") String id){
return relateService.getPerson(id);
}
网友评论