Mybatis多表模型

多表模型:

  • 多表模型分类 一对一:在任意一方建立外键,关联对方的主键。
  • 一对多:在多的一方建立外键,关联一的一方的主键。
  • 多对多:借助中间表,中间表至少两个字段,分别关联两张表的主键。
多表模型一对一操作:
  1. sql语句准备
CREATE TABLE person(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),age INT
);
INSERT INTO person VALUES (NULL,'张三',23);
INSERT INTO person VALUES (NULL,'李四',24);
INSERT INTO person VALUES (NULL,'王五',25);CREATE TABLE card(id INT PRIMARY KEY AUTO_INCREMENT,number VARCHAR(30),pid INT,CONSTRAINT cp_fk FOREIGN KEY (pid) REFERENCES person(id)
);
INSERT INTO card VALUES (NULL,'12345',1);
INSERT INTO card VALUES (NULL,'23456',2);
INSERT INTO card VALUES (NULL,'34567',3);
  1. 配置文件
<?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.duobiao.table.One">
<!--
<resultMap>:配置字段和实体对象属性的映射关系标签。
id 属性:唯一标识
type 属性:实体对象类型<id>:配置主键映射关系标签。
<result>:配置非主键映射关系标签。column 属性:表中字段名称property 属性: 实体对象变量名称
<association>:配置被包含对象的映射关系标签。property 属性:被包含对象的变量名javaType 属性:被包含对象的数据类型
--><!--配置字段和实体对象属性的映射关系--><resultMap id="oneToOne" type="card"><id column="cid" property="id" /><result column="number" property="number" /><association property="p" javaType="person"><id column="pid" property="id" /><result column="name" property="name" /><result column="age" property="age" /></association></resultMap><select id="selectAll" resultMap="oneToOne">SELECT c.id cid,number,pid,NAME,age FROM card c,person p WHERE c.pid=p.id</select>
</mapper>

核心配置文件

    <!--起别名--><typeAliases><package name="com.duobiao.bean"/></typeAliases>   <!-- mappers引入映射配置文件 --><mappers><!-- mapper 引入指定的映射配置文件   resource属性指定映射配置文件的名称 --><mapper resource="OneToOneMapper.xml"/></mappers>
  1. bean包
public class Person {private Integer id;private String name;private Integer age;
}public class Card {// 主键idprivate Integer id;// 身份证号private String number;// 所属人对象private Person p;
}
  1. 接口:
public interface OneToOneMapper {// 查询全部List<Card> selectAll();
}
  1. 测试类
 @Testpublic void selectAll() throws Exception{//1.加载核心配置文件InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");//2.获取SqlSession工厂对象SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//3.通过工厂对象获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);//4.获取OneToOneMapper接口的实现类对象OneToOneMapper mapper = sqlSession.getMapper(OneToOneMapper.class);//5.调用实现类的方法,接收结果List<Card> list = mapper.selectAll();//6.处理结果for (Card c : list) {System.out.println(c);}//7.释放资源sqlSession.close();is.close();}
一对多:

sql数据:

CREATE TABLE classes(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20)
);
INSERT INTO classes VALUES (NULL,'一班');
INSERT INTO classes VALUES (NULL,'二班');CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(30),age INT,cid INT,CONSTRAINT cs_fk FOREIGN KEY (cid) REFERENCES classes(id)
);
INSERT INTO student VALUES (NULL,'张三',23,1);
INSERT INTO student VALUES (NULL,'李四',24,1);
INSERT INTO student VALUES (NULL,'王五',25,2);
INSERT INTO student VALUES (NULL,'赵六',26,2);

bean:

public class Student {private Integer id;private String name;private Integer age;
}public class Classes {// 主键idprivate Integer id;// 班级名private String name;// 班级中所有的学生private List<Student> students;
}

配置文件:

<?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.table.OneToManyMapper"><resultMap id="oneToMany" type="classes"><id column="cid" property="id"/><result column="cname" property="name"/><!--collection:配置被包含的集合对象映射关系property:被包含对象的变量名ofType:被包含对象的实际数据类型--><collection property="students" ofType="student"><id column="sid" property="id"/><result column="sname" property="name"/><result column="sage" property="age"/></collection></resultMap><select id="selectAll" resultMap="oneToMany">SELECT c.id cid,c.name cname,s.id sid,s.name sname,s.age sage FROM classes c,student s WHERE c.id=s.cid</select>
</mapper>

测试:

    @Testpublic void selectAll() throws Exception{//1.加载核心配置文件InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");//2.获取SqlSession工厂对象SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//3.通过工厂对象获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);//4.获取OneToManyMapper接口的实现类对象OneToManyMapper mapper = sqlSession.getMapper(OneToManyMapper.class);//5.调用实现类的方法,接收结果List<Classes> classes = mapper.selectAll();//6.处理结果for (Classes cls : classes) {System.out.println(cls.getId() + "," + cls.getName());List<Student> students = cls.getStudents();for (Student student : students) {System.out.println("\t" + student);}}//7.释放资源sqlSession.close();is.close();}
多对多:

sql语句:

CREATE TABLE course(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20)
);
INSERT INTO course VALUES (NULL,'语文');
INSERT INTO course VALUES (NULL,'数学');CREATE TABLE stu_cr(id INT PRIMARY KEY AUTO_INCREMENT,sid INT,cid INT,CONSTRAINT sc_fk1 FOREIGN KEY (sid) REFERENCES student(id),CONSTRAINT sc_fk2 FOREIGN KEY (cid) REFERENCES course(id)
);
INSERT INTO stu_cr VALUES (NULL,1,1);
INSERT INTO stu_cr VALUES (NULL,1,2);
INSERT INTO stu_cr VALUES (NULL,2,1);
INSERT INTO stu_cr VALUES (NULL,2,2);

配置文件:

<?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.tableManyToManyMapper"><resultMap id="manyToMany" type="student"><id column="sid" property="id"/><result column="sname" property="name"/><result column="sage" property="age"/><collection property="courses" ofType="course"><id column="cid" property="id"/><result column="cname" property="name"/></collection></resultMap><select id="selectAll" resultMap="manyToMany">SELECT sc.sid,s.name sname,s.age sage,sc.cid,c.name cname FROM student s,course c,stu_cr sc WHERE sc.sid=s.id AND sc.cid=c.id</select>
</mapper>

测试:

 @Testpublic void selectAll() throws Exception{//1.加载核心配置文件InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");//2.获取SqlSession工厂对象SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//3.通过工厂对象获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);//4.获取ManyToManyMapper接口的实现类对象ManyToManyMapper mapper = sqlSession.getMapper(ManyToManyMapper.class);//5.调用实现类的方法,接收结果List<Student> students = mapper.selectAll();//6.处理结果for (Student student : students) {System.out.println(student.getId() + "," + student.getName() + "," + student.getAge());List<Course> courses = student.getCourses();for (Course cours : courses) {System.out.println("\t" + cours);}}//7.释放资源sqlSession.close();is.close();}
标签解释:
<resultMap>:配置字段和对象属性的映射关系标签。id 属性:唯一标识type 属性:实体对象类型<id>:配置主键映射关系标签。<result>:配置非主键映射关系标签。column 属性:表中字段名称property 属性: 实体对象变量名称<association>:配置被包含对象的映射关系标签。property 属性:被包含对象的变量名javaType 属性:被包含对象的数据类型<collection>:配置被包含集合对象的映射关系标签。property 属性:被包含集合对象的变量名ofType 属性:集合中保存的对象数据类型

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

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

相关文章

关于zkfc与zkserver频繁断开的问题

详见http://blog.csdn.net/dslztx/article/details/51596951转载于:https://www.cnblogs.com/roger888/p/7211625.html

高动态范围红外图像压缩

BF&DRC 近期看了一篇高动态范围红外图像压缩的文章&#xff0c;《New technique for the visualization of high dynamic range infrared images》.这篇文章主要利用双边滤波器把宽动态红外图像切割为基本图像和细节图像&#xff0c;再分别对基本图像和细节图像进行处理。对…

Mybatis构建sql语法

构建sql&#xff1a; 之前通过注解开发时&#xff0c;相关 SQL 语句都是自己直接拼写的。一些关键字写起来比较麻烦、而且容易出错。MyBatis 给我们提供了 org.apache.ibatis.jdbc.SQL 功能类&#xff0c;专门用于构建 SQL 语句 常用方法&#xff1a; 查询功能的实现&#xf…

Mqtt协议IOS端移植3

ServerMqFramework.h #import "MqttFramework.h"interface ServerMqFramework : MqttFramework/*** brief 得到模块控制器的句柄单例** param [in] N/A* param [out] N/A* return void* note*/(ServerMqFramework*)getMQttServerFrameInstance;- (int)callBusine…

java第三课,流程控制语句

流程控制语句条件语句&#xff1a;if语句&#xff1a;*if&#xff08;条件 boolean类型&#xff09;{ true }*if(boolean表达式){true}else&#xff5b;false结果&#xff5d;*多重 if else if(){}else if(){}else *嵌套ifSwitch语句&#xff1a;*switch(表达式){ case…

在cli命令行上显示当前数据库,以及查询表的行头信息

在$HIVE_HOME/conf/hive-site.xml文件下加入以下配置文件 <property><name>hive.cli.print.header</name><value>true</value><description>Whether to print the names of the columns in query output.</description> </proper…

两点之间最短路径:弗洛伊德算法

弗洛伊德算法是计算无向有权图中两点间最短路径的算法&#xff0c;复杂度为O(n^3)。其思路是将两点间距离分为过&#xff08;指定的&#xff09;第三点或是不过&#xff0c;然后取它们的最小值&#xff0c;如此循环就可以得到两点之间真正的最小值。 void floyd() {for (int k …

最常用的JavaScript 事件

JavaScript 事件&#xff1a; 事件指的就是当某些组件执行了某些操作后&#xff0c;会触发某些代码的执行。 更多事件&#xff1a;https://www.w3school.com.cn/jsref/dom_obj_event.asp 常用的事件&#xff1a; 属性触发时机onabort图像加载被中断onblur元素失去焦点onchange…

Codevs 1025 选菜

1025 选菜 时间限制: 1 s空间限制: 128000 KB题目等级 : 黄金 Gold题解题目描述 Description在小松宿舍楼下的不远处&#xff0c;有PK大学最不错的一个食堂——The Farmer’s Canteen&#xff08;NM食堂&#xff09;。由于该食堂的菜都很不错&#xff0c;价格也公道&#xff0c…

SAS笔记(2) RETAIN语句

本文重点&#xff1a; 使用RETIAN,INPUT在每次循环执行时保留上一次PDV中的变量值。SUM语句和SET语句会自动RETAIN变量。1. RETAIN语句 1.1 Example 1 先来看看在DATA步不使用和使用RETAIN语句的差异 没有使用RETAIN: DATA WITHOUT_1;PUT "Before the INPUT statement: &…

Hive优化策略

hive优化目标 在有限的资源下&#xff0c;运行效率高。常见问题 数据倾斜、Map数设置、Reduce数设置等 hive运行 查看运行计划 explain [extended] hql 例子 explain select no,count(*) from testudf group by no; explain extended select no,count(*) from testudf group …

POJ 3268 Silver Cow Party (最短路径)

POJ 3268 Silver Cow Party &#xff08;最短路径&#xff09; Description One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X (1 ≤ X ≤ N). A total of M (1 ≤ M ≤ 100,000) unidi…

GPU性能实时监测的实用工具

大家好,我是爱编程的喵喵。双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。现为CSDN博客专家、人工智能领域优质创作者。喜欢通过博客创作的方式对所学的…

条件随机场-应用

今天介绍CRFs在中文分词中的应用 工具&#xff1a;CRF,可以去 https://taku910.github.io/crfpp/ 下载&#xff0c;训练数据和测试数据可以考虑使用bakeoff2005,这是链接 http://sighan.cs.uchicago.edu/bakeoff2005/ 首先需要了解一些概念 字标记法——统计分词模型常用的方法…

Codeforces-808D Array Division (multiset 折半???)

题目链接&#xff1a; http://codeforces.com/problemset/problem/808/D 题意: 给定一个数列&#xff0c;移动0或1个数字&#xff0c;使数列能从某个位置分开前后两半的和相等。 思路&#xff1a; from: http://www.cnblogs.com/robin1998/p/6864278.html 我们可以假想有个隔板…

Linq中dbSet 的查询

1.Find&#xff1a;按照关键字的ID号来查询&#xff08;速度快&#xff09; 如&#xff1a; ADShiTi aDShiTi db.ADShiTis.Find(id); 2.FirstOrDefault&#xff1a;根据部分条件查询&#xff0c;显示最前的一条 如&#xff1a;按照daCID进行查找&#xff0c;有&#xff0c…

AJAX详解教程

AJAX(Asynchronous JavaScript And XML)&#xff1a;异步的 JavaScript 和 XML。本身不是一种新技术&#xff0c;而是多个技术综合。用于快速创建动态网页的技术。一般的网页如果需要更新内容&#xff0c;必需重新加载个页面。而 AJAX通过浏览器与服务器进行少量数据交换&#…

JSON转换工具

JSON的处理&#xff1a; JSON(JavaScript Object Notation)&#xff1a;是一种轻量级的数据交换格式。 它是基于 ECMAScript 规范的一个子集&#xff0c;采用完全独立于编程语言的文本格式来存储和表示数据。 简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。易于人阅…

如何获取codeforces的完整数据

推荐&#xff1a; 如何获取codeforces的完整数据&#xff1f;&#xff08;玄学方法&#xff09; http://www.cnblogs.com/Saurus/p/6220513.html转载于:https://www.cnblogs.com/cmyg/p/7232386.html

Vue与Element入门使用

Vue&#xff1a; Vue是一套构建用户界面的渐进式前端框架。只关注视图层&#xff0c;并且非常容易学习&#xff0c;还可以很方便的与其它库或已有项目整合。通过尽可能简单的API来实现响应数据的绑定和组合的视图组件。视图&#xff1a;负责页面渲染&#xff0c;主要由HTMLCSS构…