MyBatis入門實驗(8)之多對一關聯查詢
阿新 • • 發佈:2019-02-13
實驗內容
執行多對一關聯查詢
上一章實現了一對多查詢,以一為發起點,是一對多,以多為起點,則為多對一。
操作步驟
一、安裝
新增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, 2, '漢武大帝', '');
三、建立 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.TopicMapper"></mapper>
<mapper resource="mybatis/Topic.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
類,內容如下
其中,Topic 類中添加了一個 userList 屬性,用於儲存使用者資訊
public class User {
private Long id;
private String username;
private String password;
// 省略 get / set 方法
}
public class Topic {
private Long id;
private Long userId;
private String title;
private String content;
private User userList;
// 省略 get / set 方法
}
在 src/main/resources
目錄下建立目錄 mybatis
,並在該目錄下建立 Topic.xml
,內容如下
其中,User.xml 中的 resultMap 中添加了 association
屬性,用於實現多對一的邏輯。
association 必須設定的幾個屬性
property:對應JavaBean中的屬性
javaType:JavaBean的路徑
Topic.xml
<mapper namespace="tutorial.mybatis.mapper.TopicMapper">
<resultMap id="BaseResultMap" type="tutorial.mybatis.model.Role">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="user_id" jdbcType="BIGINT" property="userId" />
<result column="title" jdbcType="VARCHAR" property="title" />
<result column="content" jdbcType="VARCHAR" property="content" />
<association property="userList" javaType="tutorial.mybatis.model.User">
<id column="user_id" jdbcType="BIGINT" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
</association>
</resultMap>
<select id="listAll" resultMap="BaseResultMap">
SELECT a.id, a.username, a.password, b.id topic_id, b.title, b.content
FROM `topic` b
LEFT JOIN `user` a ON a.id = b.user_id
</select>
</mapper>
五、建立介面類
建立包 tutorial.mybatis.mapper
,並在該包下建立介面 TopicMapper
,內容如下
與上一章不同的地方:在介面類中使用註解的方式代替了XML檔案中的SQL語句
public interface TopicMapper {
List<Topic> 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 {
testMore2One(session);
} finally {
session.close();
}
}
/**
* 測試多對一
*/
public static void testMore2One(SqlSession session) {
TopicMapper topicMapper = session.getMapper(TopicMapper.class);
System.out.println("------- 獲取文章列表 --------");
printTopic(topicMapper.listAll());
}
private static void printTopic(List<Topic> list) {
if (list != null && !list.isEmpty()) {
for (Topic topic : list) {
printTopic(topic);
}
}
}
private static void printTopic(Topic topic) {
System.out.print("文章:" + topic.getTitle());
if (topic.getUser() != null) {
System.out.print(",屬於使用者:" + topic.getUser().getUsername());
}
System.out.println("");
}
}
列印結果為:
------- 獲取文章列表 --------
文章:論文學復興,屬於使用者:user1
文章:漢武大帝,屬於使用者:user2