创建数据库和表
/*
SQLyog Ultimate v8.32
MySQL - 5.6.22-log : Database - mybatis
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `mybatis`;
/*Table structure for table `orders` */
DROP TABLE IF EXISTS `orders`;
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;
/*Data for the table `orders` */
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);
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
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;
/*Data for the table `user` */
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);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
两个表的关系:
user表的主键id和orders表的外键user_id连接,从user表的角度来看,一个用户可以有多个订单,他们之间是一对多的关系;从orders表的角度来看,一个订单只属于一个用户,所以他们是一对一的关系
创建OrdersMapperQueryInterface接口及对应的xml文件
OrdersMapperQueryInterface接口
package connection;
public interface OrdersMapperQueryInterface {
}
OrdersMapperQueryInterface.xml文件
创建OrdersMapperQueryInterface接口及对应的xml文件
UserMapperQueryInterface接口
package connection;
public interface UserMppaerQueryInterface {
}
UserMapperQueryInterface.xml文件
配置SqlMapperConfig.xml
创建测试类,获取sqlSession对象
package connection;
import static org.junit.Assert.*;
import java.io.IOException;
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;
public class QueryTest {
SqlSession sqlSession = null;
/**
* 获得sqlSession
* @throws IOException
*/
@Before
public void getSession() throws IOException{
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = builder.build(Resources.getResourceAsStream("SqlMapConfig.xml"));
sqlSession = build.openSession();
}
}
一、一对一关联查询
现在要通过一个订单的信息及对应的客户信息,需要使用一对一查询。实现这个查询,需要将user类的对象加入到orders类中,然后在mapper文件中,设置user类属性的映射。
创建User类和Orders类
User类
package domain;
import java.util.Date;
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public User() {
super();
// TODO Auto-generated constructor stub
}
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
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;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address="
+ address + "]";
}
}
Orders类
package domain;
import java.util.Date;
public class Orders {
private Integer id;
private Integer userId;
private String number;
private Date createtime;
private String note;
//加入User类的对象
private User user;
public Orders() {
super();
// TODO Auto-generated constructor stub
}
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;
}
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;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Orders [id=" + id + ", userId=" + userId + ", number=" + number + ", createtime=" + createtime
+ ", note=" + note + ", user=" + user + "]";
}
}
在OrdersMapperQueryInterface接口中定义查询方法
List queryOrdersJoinUsers();
在OrdersMapperQueryInterface.xml配置文件中添加sql语句
进行测试
@Test
public void UserJoinOrders() throws Exception {
OrdersMapperQueryInterface mapper = sqlSession.getMapper(OrdersMapperQueryInterface.class);
List queryOrdersJoinUser = mapper.queryOrdersJoinUser();
for (Orders orders : queryOrdersJoinUser) {
System.out.println(orders);
}
}
二、一对多关联查询
现在我们要查询每个用户对应的订单情况,一个用户可以有多个订单,所以是一对多关联查询。
在User类中添加属性
在UserMapperQueryInterface接口中定义查询方法
List queryUserWithOrders();
在UserMapperQueryInterface.xml配置文件中添加sql语句
进行测试
@Test
public void OrdersJoinUser() throws Exception {
UserMppaerQueryInterface mapper = sqlSession.getMapper(UserMppaerQueryInterface.class);
List queryUserWithOrders = mapper.queryUserWithOrders();
for (User user : queryUserWithOrders) {
System.out.println(user.getUsername());
List ordersList = user.getOrdersList();
for (Orders orders : ordersList) {
System.out.println(orders);
}
}
}