MyBatis入門實驗(9)之多對多關聯查詢
阿新 • • 發佈:2019-02-06
實驗內容
執行多對多關聯查詢
前兩章分別實現了一對多查詢以及多對一查詢。其中多對一查詢,對於整體而言是多對一,但我們操作的是一個實體,所以對於多方的個體而言可以看成是一對一。同理,多對多查詢針對個體而言就可以看成是一對多,所以多對多查詢的處理跟一對多查詢的處理實際上是一樣一樣的。
操作步驟
一、安裝
新增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 `role` (
`id` bigint(11 ) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`name` varchar(32) NOT NULL DEFAULT '' COMMENT '角色名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT '角色';
CREATE TABLE `user_role` (
`user_id` bigint(11) unsigned NOT NULL COMMENT '主鍵',
`role_id` bigint(11) unsigned NOT NULL COMMENT '主鍵',
PRIMARY KEY (`user_id`, `role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT '使用者角色關聯表';
初始化資料
delete from `user`;
delete from `role`;
delete from `user_role`;
insert into `user` values (1, 'user1', '123');
insert into `user` values (2, 'user2', '123');
insert into `role` values (1, 'admin');
insert into `role` values (2, 'user');
insert into `user_role` values (1, 1);
insert into `user_role` values (1, 2);
insert into `user_role` 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.UserMapper"></mapper>
<mapper resource="mybatis/User.xml"></mapper>
<mapper class="tutorial.mybatis.mapper.RoleMapper"></mapper>
<mapper resource="mybatis/Role.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
及 Role
類,內容如下
其中,Topic 類中添加了一個 userList 屬性,用於儲存使用者資訊
public class User {
private Long id;
private String username;
private String password;
private List<Role> roleList;
// 省略 get / set 方法
}
public class Role {
private Long id;
private String name;
private List<User> userList;
// 省略 get / set 方法
}
在 src/main/resources
目錄下建立目錄 mybatis
,並在該目錄下建立 User.xml
以及 Role.xml
,內容如下
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="roleList" ofType="tutorial.mybatis.model.Role">
<id column="role_id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
</collection>
</resultMap>
<select id="listAll" resultMap="BaseResultMap">
SELECT a.id, a.username, a.password, c.name
FROM `user` a
LEFT JOIN `user_role` b on a.id = b.user_id
LEFT JOIN `role` c on c.id = b.role_id
</select>
</mapper>
Topic.xml
<mapper namespace="tutorial.mybatis.mapper.RoleMapper">
<resultMap id="BaseResultMap" type="tutorial.mybatis.model.Role">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<collection 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" />
</collection>
</resultMap>
<select id="listAll" resultMap="BaseResultMap">
SELECT a.id, a.name, c.username, c.password
FROM `role` a
LEFT JOIN `user_role` b on a.id = b.role_id
LEFT JOIN `user` c on c.id = b.user_id
</select>
</mapper>
五、建立介面類
建立包 tutorial.mybatis.mapper
,並在該包下建立介面 UserMapper
,內容如下
public interface UserMapper {
List<User> listAll();
}
public interface RoleMapper {
List<Role> 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 {
listUser(session);
listRole(session);
} finally {
session.close();
}
}
/**
* 查詢使用者
*/
public static void listUser(SqlSession session) {
UserMapper userMapper = session.getMapper(UserMapper.class);
System.out.println("------- 獲取使用者列表 --------");
printUser(userMapper.listAll());
}
/**
* 查詢角色
*/
public static void listRole(SqlSession session) {
RoleMapper roleMapper = session.getMapper(RoleMapper.class);
System.out.println("------- 獲取角色列表 --------");
printRole(roleMapper.listAll());
}
private static void printRole(List<Role> list) {
if (list != null && !list.isEmpty()) {
for (Role role : list) {
printRole(role);
}
}
}
private static void printRole(Role role) {
if (role == null) {
System.out.println("沒有找到資料");
} else {
System.out.println("角色:" + role.getName());
printUser(role.getUserList());
}
}
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 {
String userInfo = "ID:" + user.getId() + "名字:" + user.getUsername()+", 密碼:" + user.getPassword();
System.out.println(userInfo);
printRole(user.getRoleList());
}
}
}
列印結果為:
------- 獲取使用者列表 --------
ID:1名字:user1, 密碼:123
角色:admin
角色:user
ID:2名字:user2, 密碼:123
角色:user
------- 獲取角色列表 --------
角色:admin
ID:1名字:user1, 密碼:123
角色:user
ID:1名字:user1, 密碼:123
ID:2名字:user2, 密碼:123