1.一对一查询
1.1 一对一查询的模型
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户
SQL:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(50) DEFAULT NULL,`password` varchar(50) DEFAULT NULL,`birthday` varchar(50) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'lucy', '123', '2019-12-12');
INSERT INTO `user` VALUES ('2', 'tom','123', '2019-12-12');DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (`id` int(11) NOT NULL AUTO_INCREMENT,`ordertime` varchar(255) DEFAULT NULL,`total` double DEFAULT NULL,`uid` int(11) DEFAULT NULL,PRIMARY KEY (`id`),KEY `uid` (`uid`),CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`uid`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `orders` VALUES ('1', '2019-12-12', '3000', '1');
INSERT INTO `orders` VALUES ('2', '2019-12-12', '4000', '1');
INSERT INTO `orders` VALUES ('3', '2019-12-12', '5000', '2');
1.2 一对一查询的语句
对应的sql语句: select * from orders o,user u where o.uid=u.id;
1.3 创建Order和User实体
package com.cookie.pojo;import java.util.Date;public class User {private Integer id;private String username;private String password;private Date birthday;
}
package com.cookie.pojo;import java.util.Date;public class Order {private int id;private Date orderTime;private double total;//代表当前订单从属于哪⼀个客户private User user;}
1.4 创建OrderMapper接口
package com.cookie.mapper;import com.cookie.pojo.Order;import java.util.List;public interface OrderMapper {List<Order> findAll();
}
1.5 配置OrderMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--加载外部properties--><properties resource="jdbc.properties"></properties><environments default="development"><environment id="development"><!--当前事务交给JDBC处理--><transactionManager type="JDBC"/><!--当前使用mybatis提供的连接池--><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql:///cookie"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><!--引入映射配置文件--><mappers><mapper resource="OrderMapper.xml"/></mappers>
</configuration>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test
jdbc.username=root
jdbc.password=123456
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cookie.mapper.OrderMapper"><resultMap id="orderMap" type="com.cookie.pojo.Order"><result property="id" column="id"></result><result property="orderTime" column="orderTime"></result><result property="total" column="total"></result><association property="user" javaType="com.cookie.pojo.User"><result property="id" column="uid"></result><result property="username" column="username"></result><result property="password" column="password"></result><result property="birthday" column="birthday"></result></association></resultMap><select id="findAll" resultMap="orderMap">select * from orders o,user u where o.uid=u.id</select>
</mapper>
还可以这样配置:
<resultMap id="orderMap" type="com.cookie.pojo.Order"><result property="user.id" column="uid"></result><result property="user.username" column="username"></result><result property="user.password" column="password"></result><result property="user.birthday" column="birthday"></result></resultMap>
测试:
@Testpublic void test1() throws IOException {//加载核⼼配置文件InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);List<Order> all = mapper.findAll();for (Order order : all) {System.out.println(order);}sqlSession.close();}
2.一对多查询
2.1 一对多查询的模型
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单
2.2 一对多查询的语句
对应的sql语句: select u.*,o.id oid,o.ordertime,o.total,o.uid from user u left join orders o on u.id=o.uid;
2.3 实体类
public class User {private Integer id;private String username;private String password;private Date birthday;//代表当前⽤户具备哪些订单private List<Order> orderList;}
2.4 创建UserMapper接口
package com.cookie.mapper;import com.cookie.pojo.User;import java.util.List;public interface UserMapper {List<User> findAll();
}
2.5 配置UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cookie.mapper.UserMapper"><resultMap id="userMap" type="com.cookie.pojo.User"><result property="id" column="id"></result><result property="username" column="username"></result><result property="password" column="password"></result><result property="birthday" column="birthday"></result><collection property="orderList" ofType="com.cookie.pojo.Order"><result property="id" column="oid"></result><result property="orderTime" column="orderTime"></result><result property="total" column="total"></result></collection></resultMap><select id="findAll" resultMap="userMap">select u.*,o.id oid,o.ordertime,o.total,o.uid from user u left join orders o on u.id=o.uid;</select>
</mapper>
测试:
@Testpublic void test2() throws IOException {//加载核⼼配置文件InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> all = mapper.findAll();for (User user : all) {System.out.println(user);}sqlSession.close();}
3.多对多查询
3.1 多对多查询的模型
用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用
多对多查询的需求:查询用户同时查询出该用户的所有角色
SQL:
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (`id` int(11) NOT NULL AUTO_INCREMENT,`rolename` varchar(255) DEFAULT NULL,`roleDesc` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `sys_role` VALUES ('1', 'CTO', 'CTO');
INSERT INTO `sys_role` VALUES ('2', 'CEO', 'CEO');
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (`userid` int(11) NOT NULL,`roleid` int(11) NOT NULL,PRIMARY KEY (`userid`,`roleid`),KEY `roleid` (`roleid`),CONSTRAINT `sys_user_role_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `user` (`id`),CONSTRAINT `sys_user_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `sys_role` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `sys_user_role` VALUES ('1', '1');
INSERT INTO `sys_user_role` VALUES ('2', '1');
INSERT INTO `sys_user_role` VALUES ('1', '2');
INSERT INTO `sys_user_role` VALUES ('2', '2');
3.2 多对多查询的语句
select * from user u left join sys_user_role ur on u.id = ur.userid left join sys_role r on r.id = ur.roleid;
3.3 创建Role实体,修改User实体
package com.cookie.pojo;public class Role {private Integer id;private String roleName;private String roleDesc;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}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;}@Overridepublic String toString() {return "Role{" +"id=" + id +", roleName='" + roleName + '\'' +", roleDesc='" + roleDesc + '\'' +'}';}
}
public class User {private Integer id;private String username;private String password;private Date birthday;//代表当前用户具备哪些订单private List<Order> orderList;//代表当前用户具备哪些角色private List<Role> roleList;
}
3.4 添加UserMapper接口方法
public interface UserMapper {List<User> findAll();List<User> findAllUserAndRole();
}
3.5 配置UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cookie.mapper.UserMapper"><resultMap id="userMap" type="com.cookie.pojo.User"><result property="id" column="id"></result><result property="username" column="username"></result><result property="password" column="password"></result><result property="birthday" column="birthday"></result><collection property="orderList" ofType="com.cookie.pojo.Order"><result property="id" column="oid"></result><result property="orderTime" column="orderTime"></result><result property="total" column="total"></result></collection></resultMap><resultMap id="userRoleMap" type="com.cookie.pojo.User"><result property="id" column="userid"></result><result property="username" column="username"></result><result property="password" column="password"></result><result property="birthday" column="birthday"></result><collection property="roleList" ofType="com.cookie.pojo.Role"><result property="id" column="roleid"></result><result property="roleName" column="rolename"></result><result property="roleDesc" column="roleDesc"></result></collection></resultMap><select id="findAll" resultMap="userMap">select u.*,o.id oid,o.ordertime,o.total,o.uid from user u left join orders o on u.id=o.uid;</select><select id="findAllUserAndRole" resultMap="userRoleMap">select * from user u left join sys_user_role ur on u.id = ur.userid left join sys_role r on r.id = ur.roleid;</select>
</mapper>
测试:
@Testpublic void test3() throws IOException {//加载核⼼配置文件InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> all = mapper.findAllUserAndRole();for (User user : all) {System.out.println(user);}sqlSession.close();}