您好,登錄后才能下訂單哦!
今天小編給大家分享一下Mybatis怎么實現一對一、一對多關聯查詢的相關知識點,內容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
Mybatis實現一對一、一對多關聯查詢,關聯查詢:多個表聯合查詢,只查詢一次,通過resultMap里面的<association>
、<collection>
標簽配置一對一、一對多。
涉及的sql文件、idea工程文件:Mybatis實現一對一、一對多關聯查詢資源
班級classes、班主任teacher是一對一的關系
班級classes、學生student是一對多的關系
使用IDEA快速構建一個MyBatis工程
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com</groupId> <artifactId>sun</artifactId> <version>1.0-SNAPSHOT</version> <name>mybatisTest</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> <junit.version>5.8.2</junit.version> </properties> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.30</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.13.3</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies> <build> <resources> <resource> <!-- directory:指定資源文件的位置 --> <directory>src/main/java</directory> <includes> <!-- “**” 表示任意級目錄 “*”表示任意任意文件 --> <!-- mvn resources:resources :對資源做出處理,先于compile階段 --> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <!-- filtering:開啟過濾,用指定的參數替換directory下的文件中的參數(eg. ${name}) --> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> </build> </project>
mybatis-config.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"> <!-- 通過這個配置文件完成mybatis與數據庫的連接 --> <configuration> <!-- 引入 database.properties 文件--> <properties resource="database.properties"/> <!-- 配置mybatis的log實現為LOG4J --> <settings> <setting name="logImpl" value="LOG4J" /> </settings> <environments default="development"> <environment id="development"> <!--配置事務管理,采用JDBC的事務管理 --> <transactionManager type="JDBC"></transactionManager> <!-- POOLED:mybatis自帶的數據源,JNDI:基于tomcat的數據源 --> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${user}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!-- 將mapper文件加入到配置文件中 --> <mappers> <mapper resource="com/sun/mapper/ClassesMapper.xml"/> </mappers> </configuration>
database.properties
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai user=root password=root
MybatisUtil.java
package com.sun.utils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; /** * @author JumperSun * @date 2023-03-26-14:46 */ public class MyBatisUtil { private static SqlSessionFactory factory; static { try { InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); factory = new SqlSessionFactoryBuilder().build(is); } catch (Exception e) { e.printStackTrace(); } } public static SqlSession createSqlSession(){ return factory.openSession(false); // true為自動提交事務 } public static void closeSqlSession(SqlSession sqlSession){ if(null != sqlSession) sqlSession.close(); } }
Teacher.java
package com.sun.pojo; import lombok.Data; /** * @author JumperSun * @date 2023-03-26-14:51 */ @Data public class Teacher { private int id; private String name; }
Student.java
package com.sun.pojo; import lombok.Data; /** * @author JumperSun * @date 2023-03-26-14:53 */ @Data public class Student { private int id; private String name; }
Classes.java
package com.sun.pojo; import lombok.Data; import java.util.List; /** * @author JumperSun * @date 2023-03-26-14:52 */ @Data public class Classes { private int id; private String name; private Teacher teacher; private List<Student> studentList; }
classMapper.java
package com.sun.mapper; import com.sun.pojo.Classes; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author JumperSun * @date 2023-03-26-14:54 */ public interface ClassesMapper { List<Classes> getClassesTeacher(@Param("id") int id); List<Classes> getClassesTeacherStudentList(@Param("id") int id); }
classMapper.xml
<?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="com.sun.mapper.ClassesMapper"> <!-- 一對一關聯查詢 --> <select id="getClassesTeacher" parameterType="int" resultMap="ClassesResultMap"> select * from classes c,teacher t where c.teacher_id=t.t_id and c.c_id=#{id} </select> <resultMap type="com.sun.pojo.Classes" id="ClassesResultMap"> <!-- 實體類的字段名和數據表的字段名映射 --> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="com.sun.pojo.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </resultMap> <!-- 一對多關聯查詢 --> <select id="getClassesTeacherStudentList" parameterType="int" resultMap="ClassesResultMap2"> select * from classes c,teacher t,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and c.c_id=#{id} </select> <resultMap type="com.sun.pojo.Classes" id="ClassesResultMap2"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="com.sun.pojo.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <collection property="studentList" ofType="com.sun.pojo.Student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultMap> </mapper>
MapperTest.java
import com.sun.mapper.ClassesMapper; import com.sun.pojo.Classes; import com.sun.utils.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; /** * @author JumperSun * @date 2023-03-26-15:10 */ public class MapperTest { /** * 測試班級與班主任老師一對一的關聯關系 */ @Test public void test1() { SqlSession sqlSession = MyBatisUtil.createSqlSession(); ClassesMapper classesMapper = sqlSession.getMapper(ClassesMapper.class); List<Classes> classes = classesMapper.getClassesTeacher(1); for (Classes Classes : classes) { System.out.println(classes); } } /** * 測試班級與學生一對多關聯關系 */ @Test public void test2() { SqlSession sqlSession = MyBatisUtil.createSqlSession(); ClassesMapper classesMapper = sqlSession.getMapper(ClassesMapper.class); List<Classes> classes = classesMapper.getClassesTeacherStudentList(1); for (Classes Classes : classes) { System.out.println(classes); } } }
test1:
test2:
總結:一對一關聯查詢需要在resultMap里面配置association,一對多關聯查詢需要在resultMap里面配置collection;
List classes = classesMapper.getClassesTeacherStudentList(1); for (Classes Classes : classes) { System.out.println(classes); }} } test1: [外鏈圖片轉存中...(img-qon5qYiR-1680248446105)] test2: [外鏈圖片轉存中...(img-DZayGx8q-1680248446107)] 總結:一對一關聯查詢需要在resultMap里面配置association,一對多關聯查詢需要在resultMap里面配置collection;
以上就是“Mybatis怎么實現一對一、一對多關聯查詢”這篇文章的所有內容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。