当前位置:网站首页>Mybaits multi table query (joint query, nested query)
Mybaits multi table query (joint query, nested query)
2022-07-07 05:35:00 【PIKapikaaaa】
Multi table joint query
( One ) Overview of multi table joint query
In the development process, single table query cannot meet the project demand analysis function , For complex business , How many tables are associated , Even dozens, and the relationship between tables is quite complex . In order to be able to handle complex business functions , You must query multiple tables , stay mybatis The mapping label when the results of multi table query are provided in , It can realize one-to-one between tables 、 One to many 、 For one more 、 Many-to-many mapping .
( Two ) MyBatis Multi table query one-to-one
1. Building database tables :person( Personal table ) IdCard( ID card form )
#person surface CREATE TABLE person( p_id INT NOT NULL AUTO_INCREMENT, p_name VARCHAR(30), PRIMARY KEY(p_id) ); #IdCard surface CREATE TABLE idcard( c_id INT NOT NULL AUTO_INCREMENT, c_cardno VARCHAR(18), c_uselife DATE, c_person_id INT NOT NULL, PRIMARY KEY(c_id), FOREIGN KEY(c_person_id) REFERENCES person(p_id), UNIQUE KEY(c_cardno), UNIQUE KEY(c_person_id) ); INSERT INTO person(p_name) VALUES(' Zhang San '),(' Li Si '); INSERT INTO idcard(c_cardno,c_uselife,c_person_id) VALUES('110112199012127821','2029-10-10',1); INSERT INTO idcard(c_cardno,c_uselife,c_person_id) VALUES('120114199911103491','2030-12-01',2);
2. Prepare the project environment
1) structure maven project , Add dependency
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> <scope>runtime</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
2) Write a framework configuration file sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- To configure mybatis Environment --> <environments default="development"> <!-- Configuration environment --> <environment id="development"> <!-- Configure the type of transaction --> <transactionManager type="JDBC"></transactionManager> <!-- Configure information to connect to the database : Using data sources 【 Connection pool 】--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis002"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <package name="cn.offcn.dao"></package> </mappers </configuration>
3. Mode one : Nesting results in
1) Creating a data model Person object ,IdCard object
public class Person { private Integer id; private String name; private Idcard idcard; } public class Idcard { private Integer id; private String cardno; private Date uselife; }
2) Define the persistence layer interface PersonMapper
public interface PersonDao{ /** * according to id Inquire about person object */ Person getPersonById1(int i); }
3) Definition PersonMapper.xml Query configuration information in the file
<resultMap id="BaseResultMap" type="Person"> <id column="p_id" property="id"></id> <result column="p_name" property="name"></result> </resultMap> <resultMap id="PersonResultMap1" type="Person" extends="BaseResultMap"> <association property="idcard" javaType="Idcard"> <id column="c_id" property="id"></id> <result column="c_cardno" property="cardno"></result> <result column="c_uselife" property="uselife"></result> </association> </resultMap> <!-- According to the Department id Find Department And all information of all employees in the Department 【 Nested result query , The joint query 】 --> <select id="getPersonById1" parameterType="int" resultType="Person" resultMap="PersonResultMap1"> select p.*,c.* from person p,idcard c where p.p_id=c.c_person_id and p.p_id=#{id} </select>
4) establish PersonTest Test class
@Test // According to human id Query people and information and ID card information 【 Nested result query , Even the table query 】 public void getPersonById1(){ SqlSession session = MyBatisUtils.getSession(); PersonMapper mapper = session.getMapper(PersonMapper.class); Person person = mapper.getPersonById1(1); // Output System.out.println(person); System.out.println(person.getIdcard().toString()); MyBatisUtils.close(session); }
4. Mode two : Nested query method
1) Creating a data model Person object ,IdCard object
public class Person { private Integer id; private String name; private Idcard idcard; } public class Idcard { private Integer id; private String cardno; private Date uselife; }
2) Define the persistence layer interface PersonMapper
public interface IdCardDao{
/** * according to c_person_id Inquire about IdCard object */
Person getPersonById2(int i);
}
3) Definition PersonMapper.xml Query configuration information in the file
<!-- According to human id Query people and information and ID card information 【 nested queries , Sub table query 】 --> <select id="getPersonById2" parameterType="int" resultType="Person" resultMap="PersonResultMap2"> select * from person where p_id=#{id} </select> <resultMap id="BaseResultMap" type="Person"> <id column="p_id" property="id"></id> <result column="p_name" property="name"></result> </resultMap> <resultMap id="PersonResultMap2" type="Person" extends="BaseResultMap"> <association property="idcard" javaType="Idcard" column="p_id" select="com.chenshuang.mapper.IdcardMapper.getIdcardById"> </association> </resultMap>
4) Define the persistence layer interface IdcardMapper
public interface IdcardMapper { Idcard getIdcardById(int id); }
5) Definition IdcardMapper.xml Query configuration information in the file
<mapper namespace="com.chenshuang.mapper.IdcardMapper"> <resultMap id="BaseResultMap" type="Idcard"> <id column="c_id" property="id"></id> <result column="c_cardno" property="cardno"></result> <result column="c_uselife" property="uselife"></result> </resultMap> <select id="getIdcardById" parameterType="int" resultType="Idcard" resultMap="BaseResultMap"> select * from idcard where c_id=#{id} </select> </mapper>
6)PersonTest Add test methods to the class
@Test // According to human id Query people and information and ID card information 【 nested queries , Sub table query 】 public void getPersonById2(){ SqlSession session = MyBatisUtils.getSession(); PersonMapper mapper = session.getMapper(PersonMapper.class); Person person = mapper.getPersonById2(1); System.out.println(person); System.out.println(person.getIdcard().toString()); MyBatisUtils.close(session); }
( 3、 ... and ) MyBatis Realize one to many query
1. Create database tables :department( Departmental table ),employee( The employee table ) At the same time, set the relationship between the Department and the employee table
CREATE TABLE department( d_id INT NOT NULL AUTO_INCREMENT, d_name VARCHAR(100), PRIMARY KEY(d_id) ); CREATE TABLE employee( e_id INT NOT NULL AUTO_INCREMENT, e_name VARCHAR(30), e_gender VARCHAR(6), e_age INT, e_depart_id INT, PRIMARY KEY(e_id), FOREIGN KEY(e_depart_id) REFERENCES department(d_id) );
2. Mode one : Nesting results , How to query with tables
1) Creating a data model department and employee
public class Department { private Integer id; private String name; private List<Employee> employees; } public class Employee { private Integer id; private String name; private String gender; private Integer age; private Department depart; }
2) Department persistence layer DepartmentMapper Add query methods to the interface
public interface DepartmentMapper { Department getDepartmentById1(int id); Department getDepartmentById2(int id); }
3) Department persistence layer DepartmentMapper.xml Map file configuration
<?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"> <mapper namespace="cn.offcn.mapper.DepartmentDao"> <select id="getDepartmentById" resultMap="DepartemntResultMap2"> SELECT d.*,e.* FROM department d, employee e WHERE e.e_depart_id=d.d_id AND d.d_id=#{id} </select> <resultMap id="DepartemntResultMap" type="Department"> <id column="d_id" property="id"></id> <result column="d_name" property="name"></result> <collection property="emps" ofType="Employee"> <id column="e_id" property="id"></id> <result column="e_name" property="name"></result> <result column="e_gender" property="gender"></result> <result column="e_age" property="age"></result> </collection> </resultMap> collection: When the attribute is a set , Use collection Label mapping .
4) The test method
@Test
public void testGetDepartentById() throws Exception{
// obtain SqlSession object
SqlSession session = MyBatisUtils.getSession();
// call SqlSession establish UserDao The proxy object of the interface
DepartmentDao departmentDao = session.getMapper(DepartmentDao.class);
Department dept=departmentDao.getDepartentById(1);
// Print
System.out.println(dept);
// Commit transaction
session.commit();
// Close the connection
MyBatisUtils.close(session);
}
3. Mode two : nested queries , Query by table
1) Define the persistence layer interface of employees EmployeeMapper
public interface EmployeeDao { public List<Employee> getEmployeeByDepartId(int id); }
2) Definition DepartmentMapper.xml Query configuration information in the file
<select id="getEmployeeByDepartId" resultType="Employee"> select e_id id,e_name name,e_gender gender,e_age age from employee where e_depart_id=#{ id} </select>
3) Definition DepartmentMapper.xml The configuration file
<select id="getDepartmentById" resultMap="DepartemntResultMap"> select * from department where d_id=#{id} </select> <resultMap id="DepartemntResultMap" type="Department"> <id column="d_id" property="id"></id> <result column="d_name" property="name"></result> <collection property="emps" ofType="Employee" column="d_id" select="cn.offcn.mapper.EmployeeMapper.getEmployeeByDepartId"> </collection> </resultMap> Here it becomes a single table query , Query by table .
4) Definition EmployeeMapper.xml Query configuration information in the file
public interface EmployeeMapper {
List<Employee> getEmployeeById(int i);
}
5) Definition EmployeeMapper.xml The configuration file
<resultMap id="BaseResultMap" type="employee">
<id column="e_id" property="id"></id>
<result column="e_name" property="name"></result>
<result column="e_gender" property="gender"></result>
<result column="e_age" property="age"></result>
</resultMap>
<!-- property Set complex properties in this type javaType Data types of complex data column It means take sql Results focused Specified field select Indicates the inquiry of the survey If this query and the survey query are not in the same command space , You must add a namespace when calling -->
<resultMap id="EmployeeResultMap1" type="employee" extends="BaseResultMap">
<association property="depart" javaType="Department" column="e_depart_id" select="com.chenshuang.mapper.DepartmentMapper.getDepartmentById"></association>
</resultMap>
<!-- According to the staff id Find all information about employees and their departments 【 nested queries , Sub table query 】-->
<select id="getEmployeeById2" parameterType="int" resultType="Employee" resultMap="EmployeeResultMap1">
select * from employee where e_id=#{id}
</select>
6) The test method
@Test public void testGetDepartentById() throws Exception{ // obtain SqlSession object SqlSession session = MyBatisUtils.getSession(); // call SqlSession establish UserDao The proxy object of the interface DepartmentDao departmentDao = session.getMapper(DepartmentDao.class); Department dept=departmentDao.getDepartentById(1); // Print System.out.println(dept); // Commit transaction session.commit(); // Close the connection MyBatisUtils.close(session); }
( Four ) MyBatis Realize many to one query
1. Create database tables :department( Departmental table ),employee( The employee table ) At the same time, set the relationship between the Department and the employee table
CREATE TABLE department( d_id INT NOT NULL AUTO_INCREMENT, d_name VARCHAR(100), PRIMARY KEY(d_id) ); CREATE TABLE employee( e_id INT NOT NULL AUTO_INCREMENT, e_name VARCHAR(30), e_gender VARCHAR(6), e_age INT, e_depart_id INT, PRIMARY KEY(e_id), FOREIGN KEY(e_depart_id) REFERENCES department(d_id) );
2. Mode one : Nesting results , How to query with tables
1) Creating a data model department and employee
public class Department { private Integer id; private String name; private List<Employee> employees; } public class Employee { private Integer id; private String name; private String gender; private Integer age; private Department depart; }
2) Employee persistence EmployeeMapper Add query methods to the interface
public interface EmployeeMapper { Employee getEmployeeById1(int i); }
3) Department persistence layer EmployeeMapper.xml Map file configuration
<resultMap id="BaseResultMap" type="employee"> <id column="e_id" property="id"></id> <result column="e_name" property="name"></result> <result column="e_gender" property="gender"></result> <result column="e_age" property="age"></result> </resultMap> <!-- property Set complex properties in this type javaType Data types of complex data --> <resultMap id="EmployeeResultMap" type="employee" extends="BaseResultMap"> <association property="depart" javaType="Department"> <id column="d_id" property="id"></id> <result column="d_name" property="name"></result> </association> </resultMap> <!-- According to the staff id Find all information about employees and their departments 【 Nested result query , The joint query 】 --> <select id="getEmployeeById1" parameterType="int" resultType="Employee" resultMap="EmployeeResultMap"> SELECT e.*,d.* from employee e,department d WHERE e.e_depart_id = d.d_id AND e.e_id=#{id} </select>
4) The test method
@Test
// According to the staff id Find all information about employees and their departments 【 Nested result query , The joint query 】
public void getEmployeeById1(){
SqlSession session = MyBatisUtils.getSession();
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmployeeById1(1);
System.out.println(employee.toString()+" department ---:"+employee.getDepart().toString());
MyBatisUtils.close(session);
}
3. Mode two : nested queries , Query by table
1) Define the persistence layer interface of employees DepartmentMapper
public interface DepartmentMapper { Department getDepartmentById(int id); }
2) Employee persistence EmployeeMapper Add query methods to the interface
public interface EmployeeMapper { Employee getEmployeeById2(int i); List<Employee> getEmployeeById(int i); }
3) Definition EmployeeMapper.xml The configuration file
<resultMap id="BaseResultMap" type="employee"> <id column="e_id" property="id"></id> <result column="e_name" property="name"></result> <result column="e_gender" property="gender"></result> <result column="e_age" property="age"></result> </resultMap> <!-- property Set complex properties in this type javaType Data types of complex data column It means take sql Results focused Specified field select Indicates the inquiry of the survey If this query and the survey query are not in the same command space , You must add a namespace when calling --> <resultMap id="EmployeeResultMap1" type="employee" extends="BaseResultMap"> <association property="depart" javaType="Department" column="e_depart_id" select="com.chenshuang.mapper.DepartmentMapper.getDepartmentById"></association> </resultMap> <!-- According to the staff id Find all information about employees and their departments 【 nested queries , Sub table query 】--> <select id="getEmployeeById2" parameterType="int" resultType="Employee" resultMap="EmployeeResultMap1"> select * from employee where e_id=#{id} </select>
4) Definition DepartmentMapper Query configuration information in the file
public interface DepartmentMapper {
Department getDepartmentById(int id);
}
5) Definition DepartmentMapper.xml The configuration file
<resultMap id="BaseResultMap" type="Department">
<id column="d_id" property="id"></id>
<result column="d_name" property="name"></result>
</resultMap>
<select id="getDepartmentById" parameterType="int" resultType="Department" resultMap="BaseResultMap">
select * from department where d_id=#{id}
</select>
6) The test method
@Test // According to the staff id Find all information about employees and their departments 【 nested queries , Sub table query 】 public void getEmployeeById2(){ SqlSession session = MyBatisUtils.getSession(); EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); Employee employee = mapper.getEmployeeById2(1); System.out.println(employee.toString()+" department ---:"+employee.getDepart().toString()); MyBatisUtils.close(session); }
( 5、 ... and ) MyBatis Realize many to many query
1. Create database tables :student( Student list ),teacher( Teachers list ) At the same time, set the relationship between teachers and students Many to many
CREATE TABLE teacher( t_id INT NOT NULL auto_increment, t_name VARCHAR(30), PRIMARY KEY(t_id) ); create TABLE student_teacher( st_sid INT not NULL, st_tid INT NOT NULL, PRIMARY KEY(st_sid,st_tid), FOREIGN KEY(st_sid) REFERENCES student(s_id), FOREIGN KEY(st_tid) REFERENCES teacher(t_id) );
2. Mode one : Nesting results , How to query with tables
1) Creating a data model Teacher and Student and Intermediate class studentTeacher
public class Student { private Integer id; private String name; private String gender; private Integer age; private String birthday; private List<StudentTeacher> studentTeachers; } public class Teacher { private Integer id; private String name; private List<StudentTeacher> studentTeachers; } public class StudentTeacher { private Integer sid; private Integer tid; private Student student; private Teacher teacher; }
2) Student persistence layer StudentMapper Add query methods to the interface
public interface StudentMapper { Student getStudentById1(int i); }
3) Student persistence layer StudentMapper.xml Map file configuration
<!-- According to the students id check Student information And teacher information 【 Nested result query , The joint query 】 --> <select id="getStudentById1" parameterType="int" resultType="Student" resultMap="StudentResultMap1"> SELECT s.*,t.*,st.* FROM student s,teacher t,student_teacher st where s.id=st.st_sid AND t.t_id=st.st_tid AND s.id=#{id} </select> <resultMap id="StudentResultMap1" type="Student"> <id column="id" property="id"></id> <result column="name" property="name"></result> <result column="gender" property="gender"></result> <result column="age" property="age"></result> <result column="s_birthday" property="birthday"></result> <collection property="studentTeachers" ofType="StudentTeacher" > <result column="st_sid" property="sid"></result> <result column="st_tid" property="tid"></result> <association property="teacher" javaType="Teacher"> <id column="t_id" property="id"></id> <result column="t_name" property="name"></result> </association> </collection> </resultMap>
4) The test method
@Test
// According to the students id check Student information And teacher information 【 Nested result query , The joint query 】
public void getStudentById1(){
SqlSession session = MyBatisUtils.getSession();
StudentMapper mapper = session.getMapper(StudentMapper.class);
Student student = mapper.getStudentById1(3);
System.out.println("========= Output : ==================");
System.out.println(student);
int i=1;
for (StudentTeacher st : student.getStudentTeachers()) {
System.out.println(" teacher "+i+":"+st.getTeacher().getName());
i++;
}
System.out.println("=====================================");
MyBatisUtils.close(session);
}
3. Mode two : nested queries , Query by table
1) Creating a data model Teacher and Student and Intermediate class studentTeacher
public class Student { private Integer id; private String name; private String gender; private Integer age; private String birthday; private List<StudentTeacher> studentTeachers; } public class Teacher { private Integer id; private String name; private List<StudentTeacher> studentTeachers; } public class StudentTeacher { private Integer sid; private Integer tid; private Student student; private Teacher teacher; }
2) Student persistence layer StudentMapper Add query methods to the interface
public interface StudentMapper { Student getStudentById2(int i); }
3) Definition StudentMapper.xml The configuration file
<!-- According to the students id check Student information And teacher information 【 nested queries , Sub table query 】 --> <select id="getStudentById2" parameterType="int" resultType="Student" resultMap="StudentResultMap2"> select * from student where id=#{id} </select> <resultMap id="BaseResultMap" type="Student"> <id column="id" property="id"></id> <result column="name" property="name"></result> <result column="gender" property="gender"></result> <result column="age" property="age"></result> <result column="s_birthday" property="birthday"></result> </resultMap> <resultMap id="StudentResultMap2" type="Student" extends="BaseResultMap"> <collection property="studentTeachers" ofType="StudentTeacher" column="id" select="com.chenshuang.mapper.StudentTeacherMapper.getStudentTeacherBySid"></collection> </resultMap>
4) Definition StudentTeacherMapper Query configuration information in the file
public interface StudentTeacherMapper {
StudentTeacher getStudentTeacherBySid(int sid);
}
5) Definition StudentTeacherMapper.xml The configuration file
<resultMap id="BaseResultMap" type="StudentTeacher">
<result column="st_sid" property="sid"></result>
<result column="st_tid" property="tid"></result>
</resultMap>
<resultMap id="StudentTeacherResultMap" type="StudentTeacher" extends="BaseResultMap">
<association property="teacher" javaType="Teacher" column="st_tid" select="com.chenshuang.mapper.TeacherMapper.getTeacherById">
</association>
</resultMap>
<select id="getStudentTeacherBySid" parameterType="int" resultType="StudentTeacher" resultMap="StudentTeacherResultMap">
select * from student_teacher where st_sid=#{id}
</select>
6) Definition TeacherMapper Query configuration information in the file
public interface TeacherMapper {
Teacher getTeacherById(int id);
}
7) Definition TeacherMapper.xml The configuration file
<resultMap id="BaseResultMap" type="Teacher">
<id column="t_id" property="id"></id>
<result column="t_name" property="name"></result>
</resultMap>
<select id="getTeacherById" resultType="Teacher" parameterType="int" resultMap="BaseResultMap">
select * from teacher where t_id=#{id}
</select>
6) The test method
@Test // According to the students id check Student information And teacher information 【 nested queries , Sub table query 】 public void getStudentById2(){ SqlSession session = MyBatisUtils.getSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); Student student = mapper.getStudentById2(3); System.out.println("========= Output : =================="); System.out.println(student); int i=1; for (StudentTeacher st : student.getStudentTeachers()) { System.out.println(" teacher "+i+":"+st.getTeacher().getName()); i++; } System.out.println("====================================="); MyBatisUtils.close(session); }
边栏推荐
- Intelligent annotation scheme of entity recognition based on hugging Face Pre training model: generate doccano request JSON format
- 什么是消息队列?
- Educational Codeforces Round 22 B. The Golden Age
- EGR-20USCM接地故障继电器
- Paper reading [MM21 pre training for video understanding challenge:video captioning with pre training techniqu]
- 漏电继电器LLJ-100FS
- np. random. Shuffle and np Use swapaxis or transfer with caution
- 项目经理如何凭借NPDP证书逆袭?看这里
- 拼多多商品详情接口、拼多多商品基本信息、拼多多商品属性接口
- DJ-ZBS2漏电继电器
猜你喜欢
随机推荐
张平安:加快云上数字创新,共建产业智慧生态
nodejs获取客户端ip
Taobao commodity details page API interface, Taobao commodity list API interface, Taobao commodity sales API interface, Taobao app details API interface, Taobao details API interface
Paper reading [MM21 pre training for video understanding challenge:video captioning with pre training techniqu]
Design, configuration and points for attention of network unicast (one server, multiple clients) simulation using OPNET
Getting started with DES encryption
In memory, I moved from CSDN to blog park!
Most commonly used high number formula
高压漏电继电器BLD-20
Paper reading [open book video captioning with retrieve copy generate network]
JVM(十九) -- 字节码与类的加载(四) -- 再谈类的加载器
基于NCF的多模块协同实例
Leetcode: maximum number of "balloons"
一条 update 语句的生命经历
Design, configuration and points for attention of network specified source multicast (SSM) simulation using OPNET
做自媒体视频剪辑,专业的人会怎么寻找背景音乐素材?
High voltage leakage relay bld-20
Tablayout modification of customized tab title does not take effect
Digital innovation driven guide
《4》 Form