Mybatis 学习笔记 -- 多表查询,java 入门基础代码
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;
}
@Over
ride
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">
<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>
<select id="findAll" resultMap="accountUserMap">
select a.*,u.username,u.address from account a, user u where u.id =a.id;
</select>
<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">
<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 类中添加 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>
评论