MyBatis高级映射查询(3)
一、数据库数据和项目搭建过程
1、主要要四张表,分别为user用户信息表、items商品表、orderdetail订单明细表、orders订单表。表的结构和数据如下:
表结构
CREATE DATABASE mybatis DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
CREATE TABLE `items` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(32) NOT NULL COMMENT '商品名称',
`price` FLOAT(10,1) NOT NULL COMMENT '商品定价',
`detail` TEXT COMMENT '商品描述',
`pic` VARCHAR(64) DEFAULT NULL COMMENT '商品图片',
`createtime` DATETIME NOT NULL COMMENT '生产日期',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; CREATE TABLE `orderdetail` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`orders_id` INT(11) NOT NULL COMMENT '订单id',
`items_id` INT(11) NOT NULL COMMENT '商品id',
`items_num` INT(11) DEFAULT NULL COMMENT '商品购买数量',
PRIMARY KEY (`id`),
KEY `FK_orderdetail_1` (`orders_id`),
KEY `FK_orderdetail_2` (`items_id`),
CONSTRAINT `FK_orderdetail_1` FOREIGN KEY (`orders_id`) REFERENCES `orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_orderdetail_2` FOREIGN KEY (`items_id`) REFERENCES `items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=INNODB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; CREATE TABLE `orders` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL COMMENT '下单用户id',
`number` VARCHAR(32) NOT NULL COMMENT '订单号',
`createtime` DATETIME NOT NULL COMMENT '创建订单时间',
`note` VARCHAR(100) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`),
KEY `FK_orders_1` (`user_id`),
CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=INNODB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(32) NOT NULL COMMENT '用户名称',
`birthday` DATE DEFAULT NULL COMMENT '生日',
`sex` CHAR(1) DEFAULT NULL COMMENT '性别',
`address` VARCHAR(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
表数据
INSERT INTO `items`(`id`,`name`,`price`,`detail`,`pic`,`createtime`) VALUES (1,'台式机',3000.0,'该电脑质量非常好!!!!',NULL,'2015-02-03 13:22:53'),(2,'笔记本',6000.0,'笔记本性能好,质量好!!!!!',NULL,'2015-02-09 13:22:57'),(3,'背包',200.0,'名牌背包,容量大质量好!!!!',NULL,'2015-02-06 13:23:02'); INSERT INTO `orderdetail`(`id`,`orders_id`,`items_id`,`items_num`) VALUES (1,3,1,1),(2,3,2,3),(3,4,3,4),(4,4,2,3); INSERT INTO `orders`(`id`,`user_id`,`number`,`createtime`,`note`) VALUES (3,1,'1000010','2015-02-04 13:22:35',NULL),(4,1,'1000011','2015-02-03 13:22:41',NULL),(5,10,'1000012','2015-02-12 16:13:23',NULL); INSERT INTO `user`(`id`,`username`,`birthday`,`sex`,`address`) VALUES (1,'王五',NULL,'2',NULL),(10,'张三','2014-07-10','1','北京市'),(16,'张小明',NULL,'1','河南郑州'),(22,'陈小明',NULL,'1','河南郑州'),(24,'张三丰',NULL,'1','河南郑州'),(25,'陈小明',NULL,'1','河南郑州'),(26,'王五',NULL,NULL,NULL);
2、整个项目的目录结构
3、首先创建mybatis配置文件SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 加载属性文件 -->
<properties resource="db.properties"> </properties> <!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理,事务控制由mybatis-->
<transactionManager type="JDBC" />
<!-- 数据库连接池,由mybatis管理-->
<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> <mappers>
<mapper resource="sqlmap/Orders.xml" />
</mappers>
</configuration>
4、创建数据库配置文件db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123
5、创建映射文件orders.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zhang.dao.OrdersDao"> <select id="findOrdersUser" resultType="com.zhang.domain.OrdersCustom">
SELECT orders.*, USER.username,USER.sex,USER.address FROM orders,USER WHERE
orders.user_id = user.id
</select> <resultMap type="com.zhang.domain.Orders" id="OrdersUserResultMap">
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/> <association property="user" javaType="com.zhang.domain.User">
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
</association>
</resultMap>
<select id="findOrdersUserResultMap" resultMap="OrdersUserResultMap">
SELECT orders.*, USER.username,USER.sex,USER.address FROM orders,USER WHERE
orders.user_id = user.id
</select> <resultMap type="com.zhang.domain.Orders" id="OrdersAndOrderDetailResultMap" extends="OrdersUserResultMap" > <collection property="orderdetails" ofType="com.zhang.domain.Orderdetail">
<id column="orderdetail_id" property="id"/>
<result column="items_id" property="itemsId"/>
<result column="items_num" property="itemsNum"/>
<result column="orders_id" property="ordersId"/>
</collection>
</resultMap> <!-- 查询订单关联查询用户及订单明细,使用resultmap -->
<select id="findOrdersAndOrderDetailResultMap" resultMap="OrdersAndOrderDetailResultMap">
SELECT
orders.*,
USER.username,
USER.sex,
USER.address,
orderdetail.id orderdetail_id,
orderdetail.items_id,
orderdetail.items_num,
orderdetail.orders_id
FROM
orders,
USER,
orderdetail
WHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id
</select> <!-- 查询用户及购买的商品 -->
<resultMap type="com.zhang.domain.User" id="UserAndItemsResultMap">
<!-- 用户信息 -->
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
<!-- 订单信息一个用户对应多个订单,使用collection映射-->
<collection property="ordersList" ofType="com.zhang.domain.Orders">
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!-- 订单明细 一个订单包括 多个明细-->
<collection property="orderdetails" ofType="com.zhang.domain.Orderdetail">
<id column="orderdetail_id" property="id"/>
<result column="items_id" property="itemsId"/>
<result column="items_num" property="itemsNum"/>
<result column="orders_id" property="ordersId"/>
<!-- 商品信息一个订单明细对应一个商品-->
<association property="items" javaType="com.zhang.domain.Items">
<id column="items_id" property="id"/>
<result column="items_name" property="name"/>
<result column="items_detail" property="detail"/>
<result column="items_price" property="price"/>
</association>
</collection>
</collection>
</resultMap> <!-- 查询用户及购买的商品信息,使用resultmap -->
<select id="findUserAndItemsResultMap" resultMap="UserAndItemsResultMap">
SELECT
orders.*,
USER.username,
USER.sex,
USER.address,
orderdetail.id orderdetail_id,
orderdetail.items_id,
orderdetail.items_num,
orderdetail.orders_id,
items.name items_name,
items.detail items_detail,
items.price items_price
FROM
orders,
USER,
orderdetail,
items
WHERE orders.user_id = user.id AND orderdetail.orders_id=orders.id AND orderdetail.items_id = items.id
</select>
</mapper>
6、创建接口类OrderDao.java
package com.zhang.dao; import java.util.List; import com.zhang.domain.Orders;
import com.zhang.domain.OrdersCustom;
import com.zhang.domain.User;
public interface OrdersDao { //查询订单关联查询用户信息
public List<OrdersCustom> findOrdersUser()throws Exception; //查询订单关联查询用户使用resultMap
public List<Orders> findOrdersUserResultMap()throws Exception; //查询订单(关联用户)及订单明细
public List<Orders> findOrdersAndOrderDetailResultMap()throws Exception; //查询用户购买商品信息
public List<User> findUserAndItemsResultMap()throws Exception; //查询订单关联查询用户,用户信息是延迟加载
public List<Orders> findOrdersUserLazyLoading()throws Exception;
}
7、创建各种实体类user、orders、items、ordersdetail类
user类
package com.zhang.domain; import java.io.Serializable;
import java.util.Date;
import java.util.List; public class User implements Serializable { //属性名和数据库表的字段对应
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址 //用户创建的订单列表
private List<Orders> ordersList; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ ", birthday=" + birthday + ", address=" + address + "]";
}
public List<Orders> getOrdersList() {
return ordersList;
}
public void setOrdersList(List<Orders> ordersList) {
this.ordersList = ordersList;
} }
orders类
package com.zhang.domain; import java.util.Date;
import java.util.List; public class Orders {
private Integer id; private Integer userId; private String number; private Date createtime; private String note; //用户信息
private User user; //订单明细
private List<Orderdetail> orderdetails; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public Integer getUserId() {
return userId;
} public void setUserId(Integer userId) {
this.userId = userId;
} public String getNumber() {
return number;
} public void setNumber(String number) {
this.number = number == null ? null : number.trim();
} public Date getCreatetime() {
return createtime;
} public void setCreatetime(Date createtime) {
this.createtime = createtime;
} public String getNote() {
return note;
} public void setNote(String note) {
this.note = note == null ? null : note.trim();
} public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
} public List<Orderdetail> getOrderdetails() {
return orderdetails;
} public void setOrderdetails(List<Orderdetail> orderdetails) {
this.orderdetails = orderdetails;
} }
l
items类
package com.zhang.domain; import java.util.Date; public class Items {
private Integer id; private String name; private Float price; private String pic; private Date createtime; private String detail; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
} public Float getPrice() {
return price;
} public void setPrice(Float price) {
this.price = price;
} public String getPic() {
return pic;
} public void setPic(String pic) {
this.pic = pic == null ? null : pic.trim();
} public Date getCreatetime() {
return createtime;
} public void setCreatetime(Date createtime) {
this.createtime = createtime;
} public String getDetail() {
return detail;
} public void setDetail(String detail) {
this.detail = detail == null ? null : detail.trim();
} @Override
public String toString() {
return "Items [id=" + id + ", name=" + name + ", price=" + price
+ ", pic=" + pic + ", createtime=" + createtime + ", detail="
+ detail + "]";
} }
orderdetail类
package com.zhang.domain; public class Orderdetail {
private Integer id; private Integer ordersId; private Integer itemsId; private Integer itemsNum; //明细对应的商品信息
private Items items; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public Integer getOrdersId() {
return ordersId;
} public void setOrdersId(Integer ordersId) {
this.ordersId = ordersId;
} public Integer getItemsId() {
return itemsId;
} public void setItemsId(Integer itemsId) {
this.itemsId = itemsId;
} public Integer getItemsNum() {
return itemsNum;
} public void setItemsNum(Integer itemsNum) {
this.itemsNum = itemsNum;
} public Items getItems() {
return items;
} public void setItems(Items items) {
this.items = items;
} @Override
public String toString() {
return "Orderdetail [id=" + id + ", ordersId=" + ordersId
+ ", itemsId=" + itemsId + ", itemsNum=" + itemsNum + "]";
} }
8、创建测试类TestMy.java
package com.zhang.test; import java.io.InputStream;
import java.util.List; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test; import com.zhang.dao.OrdersDao;
import com.zhang.domain.Orders;
import com.zhang.domain.OrdersCustom;
import com.zhang.domain.User; public class TestMy {
private SqlSessionFactory sqlSessionFactory; // 此方法是在执行testFindUserById之前执行
@Before
public void setUp() throws Exception {
// 创建sqlSessionFactory
// mybatis配置文件
String resource = "SqlMapConfig.xml";
// 得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建会话工厂,传入mybatis的配置文件信息
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} //一对一查询利用resultType
@Test
public void findOrdersUser() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
OrdersDao ordersDao = sqlSession.getMapper(OrdersDao.class);
List<OrdersCustom> list=ordersDao.findOrdersUser();
System.out.println(list.size());
} //一对一查询利用resultMap
@Test
public void findOrdersUserResultMap() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
OrdersDao ordersDao = sqlSession.getMapper(OrdersDao.class);
List<Orders> list=ordersDao.findOrdersUserResultMap();
System.out.println(list.size());
} //一对多查询
@Test
public void findOrdersAndOrderDetailResultMap() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
OrdersDao ordersDao = sqlSession.getMapper(OrdersDao.class);
List<Orders> list=ordersDao.findOrdersAndOrderDetailResultMap();
System.out.println(list.size());
} //多对多查询
@Test
public void findUserAndItemsResultMap() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
OrdersDao ordersDao = sqlSession.getMapper(OrdersDao.class);
List<User> list=ordersDao.findUserAndItemsResultMap();
System.out.println(list.size());
} }
二、一对一高级查询
package com.zhang.domain; //通过此类映射订单和用户查询的结果,让此类继承包括 字段较多的pojo类
public class OrdersCustom extends Orders{ //添加用户属性
private String username;
private String sex;
private String address; public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
} }
3、编写findOrdersUser接口
4、在Orders.xml文件定义SQL映射关系
5、测试方法:
6、利用resultMap映射查询,在Orders类中添加User属性:
7、编写接口方法
8、在Orders.xml中添加ResultMap信息:
9、测试方法:
三、一对多查询
3、编写接口方法
4、在order.xml编写resultMap,继承上面的resultMap
5、测试方法
四、多对多查询
3、在Orders中添加订单明细列表属性List<OrderDetail>orderdetials,将订单的明细映射到orderdetials
4、在OrderDetail中添加Items属性,将订单明细所对应的商品映射到Items
5、编写接口方法
6、测试方法
五、知识点总结
1、resultMap与resultType:
资源下载链接:http://download.csdn.net/detail/u013865056/9907226
MyBatis高级映射查询(3)的更多相关文章
- mybatis 高级映射和spring整合之查询缓存(5)
mybatis 高级映射和spring整合之查询缓存(5) 2.0 查询缓存 2.0.1 什么是查询缓存 mybatis提供缓存,用于减轻数据压力,提高数据库性能. mybatis提供一级缓存和二级缓 ...
- 【Mybatis高级映射】一对一映射、一对多映射、多对多映射
前言 当我们学习heribnate的时候,也就是SSH框架的网上商城的时候,我们就学习过它对应的高级映射,一对一映射,一对多映射,多对多映射.对于SSM的Mybatis来说,肯定也是差不多的.既然开了 ...
- mybatis高级映射(一对一,一对多)
mybatis高级映射 一对一关联映射 需求:查询订单信息,关联查询用户信息(一个订单对应一个用户) (1)通过resultType实现 sql语句: select orders.* , USER.u ...
- mybatis 高级映射和spring整合之逆向工程(7)
mybatis 高级映射和spring整合之逆向工程(7) 4.0 逆向工程 4.1 mybatis需要程序员自己编写sql语句,mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行 ...
- mybatis 高级映射和spring整合之与Spring整合(6)
mybatis 高级映射和spring整合之mybatis与Spring整合 3.0 mybatis和spring整合(掌握) 3.1 整合思路 需求spring通过单例方式管理SqlSessionF ...
- mybatis 高级映射和spring整合之高级映射(4)
mybatis 高级映射和spring整合之高级映射 ----------------学习结构-------------------- 0.0 对订单商品数据模型进行分析 1.0 高级映射 1.1 一 ...
- (转)Mybatis高级映射、动态SQL及获得自增主键
原文:http://www.cnblogs.com/edwinchen/p/4105278.html?utm_source=tuicool&utm_medium=referral 一.动态SQ ...
- 六 mybatis高级映射(一对一,一对多,多对多)
1 订单商品数据模型 以订单商品数据为模型,来对mybaits高级关系映射进行学习.
- Mybatis高级映射、动态SQL及获得自增主键
一.动态SQL 相信大家在用mybatis操作数据库时时都会碰到一个问题,假如现在我们有一个关于作者的list authorList,需要根据authorList里已有的作者信息在数据库中查询相应作者 ...
随机推荐
- zookeeper和dubbo的关系
Dubbo建议使用Zookeeper作为服务的注册中心. 1. Zookeeper的作用: zookeeper用来注册服务和进行负载均衡,哪一个服务由哪一个机器来提供必需让调用者知 ...
- linux 再多的running也挡不住锁
再续<linux 3.10 一次softlock排查>,看运行态进程数量之多: crash> mach MACHINE TYPE: x86_64 MEMORY SIZE: GB CP ...
- React之使用Context跨组件树传递数据
--------------------------------- 讲解一 原文:https://blog.csdn.net/xuxiaoping1989/article/details/78480 ...
- Oracle分区表常见操作
Oracle分区表常用于业务中大表使用,如历史交易记录表等,提高表记录查询效率.本文主要描述范围分区表的创建.新增以及索引创建. Oracle操作分区表相关信息 显示数据库所有分区表的信息:DBA_P ...
- webpack异步加载业务模块
虽然把我们用到的JS文件全部打包一个可以节省请求数,但如果打包后的JS文件过大,那么也容易出现白屏现象,许多操作失灵.而且一些区域是点到才出现,那么相关的JS其实可以剥离出这个大JS文件外.这就涉及到 ...
- Delphi 透明窗体显示文字
设置窗体属性:BorderStyle 属性设置为 bsNoneColor 属性设置为 clWhite(白色:窗体背景色)TransparentColor 属性设置为 trueTransparentCo ...
- Hibernate 再接触 集合映射
不太重要 List 用于排序 Map key一般是user的某个字段(多半是主键 integer) package com.bjsxt.hibernate; import java.util.Has ...
- ArcGIS自定义工具箱-自增字段(可以设置初始值和步长)
ArcGIS自定义工具箱-自增字段(可以设置初始值和步长) 联系方式:谢老师,135-4855-4328,xiexiaokui#qq.com 目的:字段值初始值为设定值(默认为0),每次增加一个步长( ...
- C++学习一explicit
explicit关键字 C++中的关键字explicit主要是用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换.类构造函数默认情况下声明为隐式的即i ...
- swift中UIImageView的创建
let imageView = UIImageView() let imageView1 = UIImageView(frame: CGRectMake(, , , )) // 创建出来的UIImag ...