本小节将要介绍一对一
、一对多
的查询【技术上】。
你有可能会问,多对多怎么查,这个问题就不该问!开玩笑的,哈哈
。
其实在设计表时,一般多对多的关系就已经转化为一对多了。
一对多
就用一个学生有多本书籍来举例子吧!
image.png
table
create table `student`(
`id` int auto_increment primary key,
`name` varchar(30) not null,
`age` int
)auto_increment=10000;
create table `book`
(`id` int auto_increment primary key,
`bookName` varchar(20),
`author` varchar(10),
`studentID` int references `student`(`id`)
)auto_increment=10000;
model
public class Student {
private int id;
private String name;
private int age;
private List<Book> books;
public Student() {//无参构造函数===>创建对象
}
//getter和setter略
}
public class Book {
private int bookID;
private String bookName;
private String author;
public Book() {
}
}
//getter和setter略
dao
public interface StudentMapper {
Student findMyBooks(int id);
}
mapple.xml
方式一,直接嵌套
<select id="findMyBooks" resultMap="studentMapper">
select `student`.`id` `id`,
`student`.`name` `name`,
`student`.`age` `age`,
`book`.`id` `bookID`,
`book`.`bookName` `bookName`,
`book`.`author` `author`
from `student`,`book`
where `student`.`id` = `book`.`studentID`
and `student`.`id` = #{id}
</select>
<resultMap id="studentMapper" type="student">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<collection property="books" ofType="book">
<id property="bookID" column="bookID"/>
<result property="bookName" column="bookName"/>
<result property="author" column="author"/>
</collection>
</resultMap>
方式二:resultMap复用
<select id="findMyBooks" resultMap="studentMapper">
select `student`.`id` `id`,
`student`.`name` `name`,
`student`.`age` `age`,
`book`.`id` `bookID`,
`book`.`bookName` `bookName`,
`book`.`author` `author`
from `student`,`book`
where `student`.`id` = `book`.`studentID`
and `student`.`id` = #{id}
</select>
<resultMap id="bookMapper" type="book">
<id property="bookID" column="bookID"/>
<result property="bookName" column="bookName"/>
<result property="author" column="author"/>
</resultMap>
<resultMap id="studentMapper" type="student">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<collection property="books" resultMap="bookMapper"/>
</resultMap>
网友评论