五、Mybatis复杂映射开发

1.一对一查询

1.1 一对一查询的模型

用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户
image.png
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 一对多查询的模型

用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单
image.png

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 多对多查询的模型

用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用
多对多查询的需求:查询用户同时查询出该用户的所有角色
image.png
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();}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/475957.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

网络模型及传输基本流程

1.OSI 七层模型 OSI &#xff08; Open System Interconnection &#xff0c;开放系统互连&#xff09;七层网络模型称为开放式系统互联参考模型&#xff0c;是一个逻辑上的定义和规范; 把网络从逻辑上分为了 7 层 . 每一层都有相关、相对应的物理设备&#xff0c;比如路由器…

IDEA2021版热部署配置

第一步 Settings中搜索compiler 勾选上Build project automatically 第二步 按快捷键 CtrlAltShift/ 选择第一个Registry 勾选上 注&#xff1a;2021版IDEA 被迁移到了这里 第三步 第四步 pom.xml中添加 配置文件中添加 #springdevtools spring.devtools.restart.…

基于springboot智慧外贸平台源码和论文

网络的广泛应用给生活带来了十分的便利。所以把智慧外贸管理与现在网络相结合&#xff0c;利用java技术建设智慧外贸平台&#xff0c;实现智慧外贸的信息化。则对于进一步提高智慧外贸管理发展&#xff0c;丰富智慧外贸管理经验能起到不少的促进作用。 智慧外贸平台能够通过互…

svg之全局组件,配合雪碧图解决vue2的svg优化问题

这里是vue2中的svg的完整解决方案的另一篇。 <template><svg :class"svgClass"><use :xlink:href"#${name}"></use></svg> </template><script>export default {name: icon,props: {name: {type: String,requi…

167基于matlab的根据《液体动静压轴承》编写的有回油槽径向静压轴承的程序

基于matlab的根据《液体动静压轴承》编写的有回油槽径向静压轴承的程序&#xff0c;可显示承载能力、压强、刚度及温升等图谱.程序已调通&#xff0c;可直接运行。 167 显示承载能力、压强、刚度及温升 (xiaohongshu.com)https://www.xiaohongshu.com/explore/65d212b200000000…

IO进程线程day1作业

1、使用fgets统计给定文件行数 代码&#xff1a; #include<stdio.h> #include<string.h> #include<stdlib.h> int main(int argc, const char *argv[]) {if(argc ! 2){printf("inputs file error\n");printf("usage:./a.out filename\n&quo…

sonar-java 自定义规则

前言 最近在搞代码质量方面的项目&#xff0c;主要是针对Java语言&#xff0c;其他语言实际上也可以执行检查&#xff0c;核心原理是一样的&#xff0c;都是静态代码扫描&#xff0c;如果需要进行动态代码运行验证则可以通过单元测试的方式。以其中一个示例&#xff0c;实现自…

防火墙综合拓扑

要求&#xff1a; 1.办公区设备可以通过电信链路和移动链路上网(多对多的NAT&#xff0c;并且需要保留一个公网IP不能用来转换) 在FW1上 做安全策略 做NAT策略 这样&#xff0c;两条线就负载均衡了&#xff0c;并且相当于做了一个备份&#xff0c;一个断了就走另一条 2.分公司…

信息安全认证 | CISP证书怎么样?值得考吗?

HCIE考证研究所的朋友们&#xff0c;新年快乐&#xff01; 今天给大家说说CISP证书&#xff0c;新的一年祝大家逢考必过啊~ 01 考注册信息安全工程师证书的用处 CISP证书可作为学识和技能证明&#xff1b;求职、任职、晋升、加薪的资格凭证&#xff1b;用人单位招聘、录用劳动…

《富爸爸:巴比伦最富有的人》读书笔记

目录 作者简介 感悟 经典摘录 观点&#xff1a; 支付给自己(理解是投资自己) 观点&#xff1a;源源不断地放入金币 观点&#xff1a; 把收入的一部分留给我自己 观点&#xff1a; 从专业的人士得到建议 观点&#xff1a;一旦为自己规定了任务&#xff0c;就一定要完成 …

模型超参数寻优

参考某篇QSAR的sci论文设置 根据上图&#xff0c;我设置我的XGBoost模型&#xff1a; # 定义要搜索的超参数的候选值 param_grid {model__learning_rate: [0.1, 0.01, 0.001], # 调整学习率model__n_estimators: [50, 100, 200, 300,400,500], # 调整树的数量model__max_de…

SG7050VAN晶体振荡器规格书

SG7050VAN 晶振是EPSON/爱普生的一款额定频率73.5 MHz to 700 MHz的石英晶体振荡器&#xff0c;4脚贴片&#xff0c;7050封装常规有源晶振&#xff0c;具有小尺寸&#xff0c;高稳定性。该款有源晶体振荡器&#xff0c;可以在B : -20 C to 70 C / G : -40 C to 85 C C的温度内稳…