在 Mapper xml 中的标签里使用可以完成 1对1 关联查询
在 Mapper xml 中的标签里使用可以完成 1对多 关联查询
//sql
create table user (
id int primary key,
name varchar(400)
);
insert user info VALUES(1, 'ConstXiong1');
create table info (
user_id int primary key,
name varchar(400)
);
insert into info VALUES(1, '大熊');
create table article (
user_id int,
title varchar(400)
);
insert into article VALUES(1, '文章1');
insert into article VALUES(1, '文章2');
//Mapper xml
<!-- 1对1 -->
<select id="selectUserWithInfo" resultMap="UserWithInfo">
select user.id, user.name, info.user_id, info.name as info_name from user,info where user.id = info.user_id
</select>
<!-- 1对多 -->
<select id="selectUserWithArticles" resultMap="UserWithArticles">
select user.id, user.name, article.user_id, article.title from user,article where user.id = article.user_id
</select>
<resultMap id="UserWithInfo" type="constxiong.po.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 1对1 -->
<association property="info" javaType="constxiong.po.Info">
<id property="userId" column="user_id"/>
<result property="name" column="info_name"/>
</association>
</resultMap>
<resultMap id="UserWithArticles" type="constxiong.po.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 1对多 -->
<collection property="articles" ofType="constxiong.po.Article">
<result property="userId" column="user_id"/>
<result property="title" column="title"/>
</collection>
</resultMap>
//User.java
/**
* 用户表模型
*/
public class User {
private Integer id;
private String name;
private String mc;
private Info info;
private List<Article> articles;
public User() {
}
public User(Integer id, String name) {
this.id = id;
this.name = 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;
}
public String getMc() {
return mc;
}
public void setMc(String mc) {
this.mc = mc;
}
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", mc='" + mc + '\'' +
", info=" + info +
", articles=" + articles +
'}';
}
}
//测试代码
System.out.println("------ selectUserWithInfo ------");
user = userMapper.selectUserWithInfo();
System.out.println(user);
System.out.println("------ selectUserWithArticles ------");
user = userMapper.selectUserWithArticles();
System.out.println(user);
//打印
------ selectUserWithInfo ------
User{id=1, name='ConstXiong1', mc='null', info=Info{userId=1, name=大熊}, articles=null}
------ selectUserWithArticles ------
User{id=1, name='ConstXiong1', mc='null', info=null, articles=[Article{userId=1, title='文章1'}, Article{userId=1, title='文章2'}]}
完整 Demo:
https://javanav.com/val/a9fe4555c1614b40b0da07afeabf2a66.html