Mybatis学习笔记:
Mybatis 多表查询
表之间的关系:
一对一 : 人和身份证号是一对一的关系。一个人只能有一个身份证号,而一个身份证号只能属于一个人。
多对一(一对多):订单和用户就是多对一的关系。一个人用户可以下多个订单,多个订单只能属于一个用户
多对多 : 学生和任课老师就是多对多的关系。一个学生可以有多个任课老师,而一个任课老师可以有多个学生。
用户和账户案例
创建两张表: 用户表、账户表、让用户表和账户表具备一对多关系(在账户表中添加外键),一个用户可以有多个账户,一个账户只能属于一个用户。
# 创建账户表
create table user (
id int(11) not null auto_increment,
username varchar(32) not null comment '用户名称',
birthday datetime default null comment '生日',
sex char(1) default null comment '性别',
address varchar(256) default null comment '地址',
primary key (id)
) engine=InnoDB DEFAULT CHARSET =utf8;
# 创建账户表
create table account(
id int(11) not null comment '编号',
uid int(11) default null comment '用户金额',
money double default null comment '金额',
primary key(id),
key FK_Reference_8 (uid),
constraint FK_Reference_8 foreign key(uid) references user(id)
)engine=InnoDB DEFAULT CHARSET =utf8;
在表中添加数据:
目录结构:
建立用户实体类和账户实体类,并在实体类中体现相应关系
创建用户实体类:
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
//一对多关系映射,主表实现应该包含从表实体的集合
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
创建账户实体类:
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
private User user;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
", user=" + user +
'}';
}
}
创建AccountUser类:
public class AccountUser extends Account{
private String username;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return super.toString()+" AccountUser{" +
"username='" + username + '\'' +
", address='" + address + '\'' +
'}';
}
}
实现用户的dao接口:
public interface IUserDao{
/**
* 查询所有用户
*
* @return
*/
List<User> findAll();
/**
* 根据id查询一个用户id
* @param userId
*/
User findById(Integer userId);
}
实现账户的dao接口:
public interface IAccountDao{
/**
* 查询所有账户
* @return
*/
List<Account> findAll();
/**
* 查询所有账户,并且带有用户名称和地址信息
* @return
*/
List<AccountUser> findAllAccount();
}
实现一对一关系:
创建账户配置文件IAccountDao.xml:实现查询账户时同时的到账户对应的用户信息
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ly.dao.IAccountDao">
<!-- 定义封装account和user的resultMap-->
<resultMap id="accountUserMap" type="account">
<id property="id" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<association property="user" column="uid" javaType="User">
<id property="id" column="id"></id>
<result column="username" property="username"></result>
<result column="address" property="address"></result>
<result column="sex" property="sex"></result>
<result column="birthday" property="birthday"></result>
</association>
</resultMap>
<!-- 配置查询所有-->
<!--使用resultMap属性实现单表映射关系,并在Account类中添加User类属性,实现一对一查询-->
<select id="findAll" resultMap="accountUserMap">
select a.*,u.username,u.address from account a, user u where u.id =a.id;
</select>
<!-- 配置查询所有,同时包含所有账户-->
<!--通过AccountUser继承父类Account的方法实现一对一查询(不常用)-->
<select id="findAllAccount" resultType="AccountUser">
select u.*,a.id as aid,a.uid,a.money from account a, user u where u.id =a.uid;
</select>
</mapper>
测试代码:一对一操作
public class AccountTest {
private InputStream in;
private SqlSession sqlSession;
private IAccountDao accountDao;
@Before//再测试方法执行之前执行
public void init() throws Exception{
//1.读取配置文件,生成字节输入流
in= Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂,获取SqlSessionFactory对象
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
//3.使用工厂生产SqlSession对象
sqlSession=factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
accountDao=sqlSession.getMapper(IAccountDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy() throws Exception{
//提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
//使用代理对象执行方法
List<Account> accounts=accountDao.findAll();
for (Account account : accounts){
System.out.println("每个account信息");
System.out.println(account);
System.out.println(account.getUser());
}
}
/**
* 测试查询所有账户,包括用户名和地址
*/
@Test
public void testFindAllAccountUser(){
//使用代理对象执行方法
List<AccountUser> aus=accountDao.findAllAccount();
for (AccountUser au : aus){
System.out.println(au);
}
}
}
测试 testFindAll方法
测试testFindAllAccountUser方法
实现一对多关系:
创建用户配置文件:IUserDao.xml:实现查询用户同时得到用户下的所有账户
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ly.dao.IUserDao">
<!--定义User的resultMap-->
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<!--配置user对象中accounts集合的映射-->
<!--实现一对多关系,首先我们应该在User类中添加List<Account>集合属性
collection:集合 ofType:集合中元素的类型-->
<collection property="accounts" ofType="account">
<id column="aid" property="id"></id>
<result column="uid" property="uid"></result>
<result column="money" property="money"></result>
</collection>
</resultMap>
<!-- 配置查询所有-->
<select id="findAll" resultMap="userAccountMap">
select * from user u left outer join account a on u.id =a.uid
</select>
</mapper>
测试代码:一对多代码
public class UserTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
@Before//再测试方法执行之前执行
public void init() throws Exception{
//1.读取配置文件,生成字节输入流
in= Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂,获取SqlSessionFactory对象
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
//3.使用工厂生产SqlSession对象
sqlSession=factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
userDao=sqlSession.getMapper(IUserDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy() throws Exception{
//提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
//5.使用代理对象执行方法
List<User> users=userDao.findAll();
for (User user : users){
System.out.println("-----------每个用户的信息----------");
System.out.println(user);
System.out.println(user.getAccounts());
}
}
}
测试testFindAll方法:
用户和角色案例
实现多对多关系: 一个用户可以又多个角色,一个角色可以赋予多个用户
建立两张表:让用户表和角色表具有多对多的关系。需要使用中间表,中间表中包含各子的主键,在中间表中是外键
#创建角色表
create table role(
id int(11) not null comment '编号',
role_name varchar(30) default null comment '角色名称',
role_desc varchar(60) default null comment '角色描述',
primary key(id)
)engine=InnoDB default charset=utf8;
//#创建用户角色表(中间表)
create table user_role(
uid int(11) not null comment '用户编号',
rid int(11) not null comment '角色编号',
primary key (uid,rid),
key FK_Reference_10(RID),
constraint FK_Reference_10 foreign key (rid) references role (id),
constraint FK_Reference_9 foreign key(uid) references user (id)
)engine=InnoDB default charset=utf8;
目录结构:
建立两个实体类:
实体类Role:
/**
* @Author: Ly
* @Date: 2020-07-16 08:22
*/
public class Role implements Serializable {
private Integer roleId;
private String roleName;
private String roleDesc;
//多对多的关系映射,一个角色可以赋予多个用户
private List<User> users;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
@Override
public String toString() {
return "Role{" +
"roleId=" + roleId +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
实体类User:
/**
* @Author: Ly
* @Date: 2020-07-12 11:15
*/
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
//多对多的关系映射,一个用户可以具备多个角色
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
创建Role类的dao接口:
/**
* @Author: Ly
* @Date: 2020-07-16 08:24
*/
public interface IRoleDao {
/**
* 查询所有角色
* @return
*/
List<Role> findAll();
}
创建User类的dao接口:
/**
* @Author: Ly
* @Date: 2020-07-12 11:29
*/
public interface IUserDao {
/**
* 查询所有用户
*
* @return
*/
List<User> findAll();
}
配置IRoleDao的映射配置文件:IRoleDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ly.dao.IRoleDao">
<!-- 订单查询关联用户的resultMap
将整个查询的结果映射到cn.itcast.mybatis.po.Orders中
-->
<resultMap type="Role" id="roleMap">
<!-- 配置映射的订单信息 -->
<!-- id:指定查询列中的唯 一标识,订单信息的中的唯 一标识,如果有多个列组成唯一标识,配置多个id
column:订单信息的唯 一标识 列
property:订单信息的唯 一标识 列所映射到Orders中哪个属性
-->
<id column="rid" property="roleId"/>
<result column="role_name" property="roleName"/>
<result column="role_desc" property="roleDesc"/>
<collection property="users" ofType="User">
<id column="id" property="id"></id>
<result column="username" property="username"></result>
<result column="address" property="address"></result>
<result column="sex" property="sex"></result>
<result column="birthday" property="birthday"></result>
</collection>
</resultMap>
<!-- 配置查询所有-->
<!--<select id="findAll" resultMap="roleMap">-->
<select id="findAll" resultMap="roleMap">
select u.*,r.id as rid,r.role_name,r.role_desc from role r
left outer join user_role ur on r.id = ur.rid
left outer join user u on u.id = ur.uid
</select>
</mapper>
配置IUserDao的映射配置文件:IUserDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ly.dao.IUserDao">
<!--定义User的resultMap-->
<resultMap id="userMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<collection property="roles" ofType="role">
<id property="roleId" column="rid"></id>
<result property="roleName" column="role_name"></result>
<result property="roleDesc" column="role_desc"></result>
</collection>
</resultMap>
<!-- 配置查询所有-->
<select id="findAll" resultMap="userMap">
select u.*,r.id as rid,r.role_name,r.role_desc from user u
left outer join user_role ur on u.id = ur.uid
left outer join role r on r.id = ur.rid
</select>
</mapper>
测试代码:角色对用户查询
public class RoleTest {
private InputStream in;
private SqlSession sqlSession;
private IRoleDao roleDao;
@Before//再测试方法执行之前执行
public void init() throws Exception{
//1.读取配置文件,生成字节输入流
in= Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂,获取SqlSessionFactory对象
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
//3.使用工厂生产SqlSession对象
sqlSession=factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
roleDao=sqlSession.getMapper(IRoleDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy() throws Exception{
//提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
//使用代理对象执行方法
List<Role> roles=roleDao.findAll();
for (Role role :roles){
System.out.println("--角色信息--");
System.out.println(role);
System.out.println(role.getUsers());
}
}
}
测试结果:
测试代码:用户对角色查询
public class UserTest {
private InputStream in;
private SqlSession sqlSession;
private IUserDao userDao;
@Before//再测试方法执行之前执行
public void init() throws Exception{
//1.读取配置文件,生成字节输入流
in= Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂,获取SqlSessionFactory对象
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
//3.使用工厂生产SqlSession对象
sqlSession=factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
userDao=sqlSession.getMapper(IUserDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy() throws Exception{
//提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
//5.使用代理对象执行方法
List<User> users=userDao.findAll();
for (User user :users){
System.out.println("----每个用户的信息-----");
System.out.println(user);
System.out.println(user.getRoles());
}
}
}
测试结果: