今日内容
-
MyBatis的多表操作
- 一对一查询
- 一对多查询
- 多对多查询
-
MyBatis注解开发
- 常用注解
- 使用MyBatis注解实现增删改查操作
- 复杂映射(注解代替< resultMap>)
- 注解一对一查询
- 注解一对多查询
- 注解多对多查询
-
SSM整合
- 原始整合
- ssm方式整合
1. MyBatis的多表操作
1.1 一对一查询
1. 一对一查询数据库模型
设有一个orders(订单表)和一个user(用户表),一个订单只属于一个用户
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户
数据库构成:
2. 一对一查询的语句
对应的sql语句:select * from orders o,user u where o.uid=u.id;
查询结果:
3. 创建User,Order对应实体以及OrderMapper接口
Order中的uid替换成User类创建,表示订单属于哪个用户
OrderMapper中创建findAll()方法,返回值是List
4. 配置OrderMapper.xml
<!--id:这个标签的名称 type:类型地址,此处用自定义别名代替-->
<resultMap id="orderMap" type="order">
<!--手动指定字段与实体属性的映射关系
column: 数据表的字段名称
property:实体的属性名称
-->
<id column="oid" property="id"></id>
<result column="ordertime" property="ordertime"></result>
<result column="total" property="total"></result>
<!--
property:当前实体中的属性名称(private User user)
javaType:当前实体(order)中的属性类型(User)
-->
<association property="user" javaType="user">
<id column="uid" property="id"></id>
<result column="username" property="username"></result>
<result column="password" property="password"></result>
<result column="birthday" property="birthday"></result>
</association>
</resultMap>
<select id="findAll" resultMap="orderMap">
SELECT *,o.id oid FROM orders o,USER u WHERE o.uid=u.id
</select>
5. 测试结果
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
List<Order> all = mapper.findAll();
for(Order order : all){
System.out.println(order);
}
结果:
1.2 一对多查询
1. 一对多查询的模型分析
用户表(user)和订单表(order)的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单
2. 一对多查询的语句
查询语句:select *,o.id oid from user u left join orders o on u.id=o.uid;
3. User实体与UserMapper接口
User实体中需要添加 List orderList存储用户的各个订单
UserMapper中创建findAll() 方法,返回值是List
4. 配置UserMapper.xml
<resultMap id="userMap" type="user">
<id column="uid" property="id"></id>
<result column="username" property="username"></result>
<result column="password" property="password"></result>
<result column="birthday" property="birthday"></result>
<!--配置集合
property 集合名称
ofType 当前集合数据类型
-->
<collection property="orderList" ofType="order">
<!--封装order的数据-->
<id column="oid" property="id"></id>
<result column="ordertime" property="ordertime"></result>
<result column="total" property="total"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="userMap">
SELECT *,o.id oid FROM USER u,orders o WHERE u.id=o.uid
</select>
5. 测试结果
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAll();
for(User user : all){
System.out.println(user);
}
输出语句为user类中的属性全部打印出来,其中orderList中的内容也被全部变量
1.3 多对多查询
1. 多对多查询的模型及分析
用户表(user)和角色表(role)的关系为,一个用户有多个角色,一个角色被多个用户使用
其原理和一对多查询差不多,只不过就是角色可以被多个人使用
多对多查询的需求:查询用户同时查询出该用户的所有角色
2. 多对多查询的语句
对应的sql语句:
SELECT
u.*,r.id rid,r.rolename
FROM
USER u,sys_user_role ur,sys_role r