mybatis的一对多

1、配置文件

db.properties

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
db.username=root
db.password=123456

SqlMapConfig.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6
 7     <!-- 加载java的配置文件 -->
 8     <properties resource="config/db.properties"/>
 9
10     <!-- 配置mybatis的环境信息,与spring整合,该信息由spring来管理 -->
11     <environments default="development">
12         <environment id="development">
13             <!-- 配置JDBC事务控制,由mybatis进行管理 -->
14             <transactionManager type="JDBC"></transactionManager>
15             <!-- 配置数据源,采用mybatis连接池 -->
16             <dataSource type="POOLED">
17                 <property name="driver" value="${db.driver}" />
18                 <property name="url" value="${db.url}" />
19                 <property name="username" value="${db.username}" />
20                 <property name="password" value="${db.password}" />
21             </dataSource>
22         </environment>
23     </environments>
24
25     <!-- 加载映射文件 -->
26     <mappers>
27         <mapper resource="com/xiaostudy/oneTOmany/mapper.xml" />
28     </mappers>
29
30 </configuration>

mapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="com.xiaostudy.oneTOmany.Mapper">
 6
 7     <!-- ========================================================================================== -->
 8     <!-- 一对多之resultMap1 -->
 9     <select id="findOfTeacher" resultMap="OfTeacher">
10         select * from t_student s, t_teacher t where s.sid=t.tid and t.tid=#{id}
11     </select>
12     <resultMap type="com.xiaostudy.oneTOmany.Teacher" id="OfTeacher">
13         <id column="tid" property="id"/>
14         <result column="tname" property="name"/>
15         <collection  property="student" ofType="com.xiaostudy.oneTOmany.Student" ><!-- javaType="HashSet" -->
16             <id column="sid" property="sid"></id>
17             <result column="sname" property="sname"/>
18         </collection>
19     </resultMap>
20    <!-- ========================================================================================== -->
21
22     <!-- ========================================================================================== -->
23     <!-- 一对多之resultMap2 -->
24     <select id="findOfTeachers" resultMap="OfTeachers">
25         select * from t_student2 s, t_teacher t where s.sid=t.tid and t.tid=#{id}
26     </select>
27     <resultMap type="com.xiaostudy.oneTOmany.Teacher" id="OfTeachers">
28         <id column="tid" property="id"/>
29         <result column="tname" property="name"/>
30         <collection property="student" ofType="com.xiaostudy.oneTOmany.Student" select="getStudents" column="sid"/>
31     </resultMap>
32
33     <select id="getStudents" parameterType="int" resultType="com.xiaostudy.oneTOmany.Student">
34         select * from t_student2 s where s.sid = #{id}
35     </select>
36    <!-- ========================================================================================== -->
37
38     <!-- ========================================================================================== -->
39     <!-- 一对多之resultMap3 -->
40     <select id="findOfTeachers2" resultMap="OfTeachers2">
41         select * from t_student2 s, t_teacher t where s.sid=t.tid and t.tid=#{tid}
42     </select>
43     <resultMap type="com.xiaostudy.oneTOmany.Teacher" id="OfTeachers2">
44         <id column="tid" property="id"/>
45         <result column="tname" property="name"/>
46         <collection property="student" ofType="com.xiaostudy.oneTOmany.Student" select="getStudents2" column="id"/>
47     </resultMap>
48
49     <select id="getStudents2" resultType="com.xiaostudy.oneTOmany.Student">
50         select * from t_student2 s where s.sid = #{sid}
51     </select>
52    <!-- ========================================================================================== -->
53 </mapper>

2、domain类

Student.java

 1 package com.xiaostudy.oneTOmany;
 2
 3 public class Student {
 4     private int sid;
 5     private String sname;
 6     private Teacher teacher;
 7
 8     public int getSid() {
 9         return sid;
10     }
11
12     public void setSid(int sid) {
13         this.sid = sid;
14     }
15
16     public String getSname() {
17         return sname;
18     }
19
20     public void setSname(String sname) {
21         this.sname = sname;
22     }
23
24     public Teacher getTeacher() {
25         return teacher;
26     }
27
28     public void setTeacher(Teacher teacher) {
29         this.teacher = teacher;
30     }
31
32     @Override
33     public String toString() {
34         return "Student [sid=" + sid + ", sname=" + sname + ", teacher=" + teacher + "]";
35     }
36
37 }

Teacher.java

 1 package com.xiaostudy.oneTOmany;
 2
 3 import java.util.Set;
 4
 5 public class Teacher {
 6     private int id;
 7     private String name;
 8     private Set<Student> student;
 9
10     public Set<Student> getStudent() {
11         return student;
12     }
13
14     public void setStudent(Set<Student> student) {
15         this.student = student;
16     }
17
18     public int getId() {
19         return id;
20     }
21
22     public void setId(int id) {
23         this.id = id;
24     }
25
26     public String getName() {
27         return name;
28     }
29
30     public void setName(String name) {
31         this.name = name;
32     }
33
34     @Override
35     public String toString() {
36         return "Teacher [id=" + id + ", name=" + name + ", student=" + student + "]";
37     }
38
39 }

3、代理类Mapper.java

 1 package com.xiaostudy.oneTOmany;
 2
 3 import java.util.List;
 4
 5 public interface Mapper {
 6
 7     // 一对多之resultMap1
 8     public List<Teacher> findOfTeacher(int id);
 9
10     // 一对多之resultMap2
11     public List<Teacher> findOfTeachers(int id);
12
13     // 一对多之resultMap3
14     public Teacher findOfTeachers2(int id);
15
16 }

4、测试类

 1 package com.xiaostudy.oneTOmany;
 2
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.List;
 6 import java.util.Set;
 7
 8 import org.apache.ibatis.io.Resources;
 9 import org.apache.ibatis.session.SqlSession;
10 import org.apache.ibatis.session.SqlSessionFactory;
11 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
12 import com.xiaostudy.oneTOmany.Teacher;
13
14 /**
15  * @desc 测试类
16  * @author xiaostudy
17  *
18  */
19 public class MybatisTest {
20
21     public static void main(String[] args) throws IOException {
22         String resource = "config/SqlMapConfig.xml";
23         InputStream inputStream = Resources.getResourceAsStream(resource);
24
25         // 创建SqlSessionFactory
26         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
27
28         // 创建SqlSession
29         SqlSession sqlSession = sqlSessionFactory.openSession();
30
31         // 获取一个代理dao实现
32         Mapper mapper = sqlSession.getMapper(Mapper.class);
33
34         //一对多之resultMap1
35 //        List<Teacher> list = mapper.findOfTeacher(3);
36
37         //一对多之resultMap2
38         List<Teacher> list = mapper.findOfTeachers(2);
39         /*Teacher teacher = list.get(0);
40         System.out.println(teacher.getId());
41         System.out.println(teacher.getName());
42         Set<Student> student = teacher.getStudent();
43         for(Student s : student) {
44             System.out.println(s);
45         }*/
46         //一对多之resultMap3
47 //        Teacher t = mapper.findOfTeachers2(2);
48
49         for(Teacher t : list) {
50             System.out.println(t);
51         }
52
53 //        System.out.println(list.get(0));
54 //        System.out.println(t);
55 //        System.out.println(list);
56
57         sqlSession.close();
58
59     }
60
61 }

5、数据库

t_teacher表

t_student2表



mybatis的一对多

原文地址:https://www.cnblogs.com/xiaostudy/p/9588985.html

时间: 2024-11-05 13:04:24

mybatis的一对多的相关文章

mybatis的一对多,多对一,以及多对对的配置和使用

1.本文章是无意中看见易百教程的Mybatis教程才注意到这个问题,平时都仅仅是在用CRUD,忽略了这方面的问题,真实十分羞愧 2.首先我们开始对mybatis的一对多的探究 根据这个应用场景,我们需要获取在查询一个用户信息的时候还要去读取这个用户发布的帖子 现在我们来看一看用户级联文章在JavaBean中的编写方式,这就是一对多在JavaBean中的配置 现在我们再来看一看Mybatis的Mapper该如何编写一对多?很简单,就是在resultMap标签中配置<collection>标签,用

Mybatis学习——一对多关联表查询

1.实体类 1 public class Student { 2 private int id; 3 private String name; 4 } 5 public class Classes { 6 private int id; 7 private String name; 8 private Teacher teacher; 9 private List<Student> students; 10 } 2.映射文件 1 <?xml version="1.0"

mybatis实现一对多连接查询

问题:两个对象User和Score,它们之间的关系为一对多. 底层数据库为postgresql,ORM框架为mybatis. 关键代码如下: mybatis配置文件如下: mybatis.xml文件内容为: Java代码   <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN&q

mybatis 中一对多关系简单应用

1:应用场景 主要需要实现是一个实体类中存在一个字段,该字段为一个集合,集合存放的是另外一个实体类类型 如教室类(Class)中有一个学生类(student)的集合,即表示一个教室中 存在多个学生 项目保存路径: D:\海同\mybatis\9.16\FirstMybatis 2:相关代码 创建数据库中表语句 CREATE TABLE teacher( t_id INT PRIMARY KEY AUTO_INCREMENT, t_name VARCHAR(20) ); CREATE TABLE

Mybatis的一对多(collection)和一对一(association)查询

1.mybatis支持映射复杂的查询结果集 2.表之间的关系 3.实体及其对应关系: @Data @EqualsAndHashCode(callSuper = false) public class TestOne implements Serializable { private static final long serialVersionUID = 1L; private Integer id; // private String nickname; // private List<Tes

Mybatis 中一对多,多对一的配置

现在有很多电商平台,就拿这个来说吧.顾客跟订单的关系,一个顾客可以有多张订单,但是一个订单只能对应一个顾客. 一对多的顾客 <?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&quo

MyBatis Review——一对多关系映射配置

示例: 查询订单表及订单明细信息. 编写sql查询语句: SELECT orders.*, USER .username ,USER .sex, USER .address, orderdetail.id as orderdetail_id, orderdetail.items_id, orderdetail.items_num, orderdetail.orders_id FROM orders, USER, orderdetail WHERE orders.user_id = USER .i

mybatis的一对多查询

创建实体类对象 class XXX{ string xxx, string xxx, List<MMM> mmm, } mybatis  xml 文件的编写两种方式 <!--  第一种方式 黑域名一对多的关系 --><select id="getListDns" resultMap="listDns"> SELECT t1.*,t2.DnsServerIp ,t2.ParseIp ,t2.DnsSrcPort ,t2.VisitT

mybatis collection 一对多关联查询,单边分页的问题总结!

若想直接通过sql实现多级关联查询表结构得有2 个必不可少的字段:id ,parentId,levelId id:主键id, parentId:父id levelId:表示第几级(表本身关联查询的时候需要用到,不然会有重复数据) 利用mybatis collection 实现一对多关联查询 Dto:(一级) public class ProvinceInfoDTO implements Serializable { private String id; private String name;