MyBatis入門實驗(7)之一對多關聯查詢
阿新 • • 發佈:2019-02-12
實驗內容
執行一對多關聯查詢
操作步驟
一、安裝
新增Maven依賴(本文使用版本為3.4.6)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId >mysql-connector-java</artifactId>
<version>5.1.42</version>
</dependency>
二、建立資料庫及表結構
分別建立使用者表及文章表,一個使用者擁有多篇文章,典型的一對多案例
CREATE TABLE `user` (
`id` bigint(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`username` varchar(32) NOT NULL COMMENT '使用者名稱',
`password` varchar(64) NOT NULL COMMENT '密碼',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT '使用者';
CREATE TABLE `topic` (
`id` bigint(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`user_id` bigint(11) unsigned NOT NULL COMMENT '使用者',
`title` varchar(32) NOT NULL DEFAULT '' COMMENT '標題',
`content` varchar(255) NOT NULL DEFAULT '' COMMENT '密碼',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT '文章';
初始化資料
delete from `user`;
delete from `topic`;
insert into `user` values (1, 'user1', '123');
insert into `user` values (2, 'user2', '123');
insert into `topic` values (1, 1, '論文學復興', '');
insert into `topic` values (2, 1, '漢武大帝', '');
三、建立 Mybatis 配置檔案
在 src/main/resources
目錄下建立 mybatis-config.xml
檔案,內容如下
<configuration>
<properties resource="jdbc.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 載入XML,同時載入介面類 -->
<mappers>
<mapper class="tutorial.mybatis.mapper.UserMapper"></mapper>
<mapper resource="mybatis/User.xml"></mapper>
</mappers>
</configuration>
在 src/main/resources
目錄下建立 jdbc.properties
檔案,內容如下
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/tutorial_mybatis?characterEncoding=utf-8&useSSL=true
jdbc.username=root
jdbc.password=
四、建立實體類
建立包 tutorial.mybatis.model
,並在該包下建立 User
及 Topic
類,內容如下
其中,User 類中添加了一個 roleList 屬性,用於儲存使用者的文章列表
public class User {
private Long id;
private String username;
private String password;
private List<Topic> roleList;
// 省略 get / set 方法
}
public class Topic {
private Long id;
private Long userId;
private String title;
private String content;
// 省略 get / set 方法
}
在 src/main/resources
目錄下建立目錄 mybatis
,並在該目錄下建立 User.xml
,內容如下
其中,User.xml 中的 resultMap 中添加了 collection
屬性,用於實現一對多的邏輯,從標籤名也可以看出這個屬性對應的是一個集合。
這個標籤只是起到了一個組合的作用,將其內部的幾個屬性值組裝成一個物件集合,所以對於SQL而言,關注的是其內部的列設定
collection 必須設定的幾個屬性
property:對應JavaBean中的屬性
ofType:JavaBean的路徑
User.xml
<mapper namespace="tutorial.mybatis.mapper.UserMapper">
<resultMap id="BaseResultMap" type="tutorial.mybatis.model.User">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
<collection property="topicList" ofType="tutorial.mybatis.model.Topic">
<id column="topic_id" jdbcType="BIGINT" property="id" />
<result column="title" jdbcType="VARCHAR" property="title" />
<result column="content" jdbcType="VARCHAR" property="content" />
</collection>
</resultMap>
<select id="listAll" resultMap="BaseResultMap">
SELECT a.id, a.username, a.password, b.id topic_id, b.title, b.content
FROM `user` a
LEFT JOIN `topic` b ON a.id = b.user_id
</select>
</mapper>
五、建立介面類
建立包 tutorial.mybatis.mapper
,並在該包下建立介面 UserMapper
,內容如下
public interface UserMapper {
List<User> listAll();
}
六、構建
準備工作就緒,開始最終章,建立啟動類 MybatisConfig
,內容如下:
public class MybatisConfig {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
SqlSession session = sqlSessionFactory.openSession();
try {
testOne2More(session);
} finally {
session.close();
}
}
/**
* 一對多查詢
*/
public static void testOne2More(SqlSession session) {
UserMapper userMapper = session.getMapper(UserMapper.class);
System.out.println("------- 獲取使用者列表 --------");
printUser(userMapper.listAll());
}
private static void printUser(List<User> list) {
if (list != null && !list.isEmpty()) {
for (User user : list) {
printUser(user);
}
}
}
private static void printUser(User user) {
if (user == null) {
System.out.println("沒有找到資料");
} else {
System.out.println("使用者:" + user.getUsername());
printTopic(user.getTopicList());
}
}
private static void printTopic(List<Topic> list) {
if (list != null && !list.isEmpty()) {
for (Topic topic : list) {
printTopic(topic);
}
}
}
private static void printTopic(Topic topic) {
if (topic == null) {
System.out.println("沒有找到文章資料");
} else {
System.out.println("文章:" + topic.getTitle());
}
}
}
列印結果為:
使用者:user1
文章:論文學復興
文章:歷史
使用者:user2
可以看出,使用者user1擁有兩篇文章,而使用者user2沒有文章