1. 程式人生 > >MyBatis關聯查詢(一對一)

MyBatis關聯查詢(一對一)

我們以一個例子demo的形式,說明Mybatis的一對一關聯查詢

設計teachers表

classes表設定外來鍵

classes表

classes表是課程表,teachers表是教師資訊表

這裡是一對一的關聯關係,當然實際中一般不是這樣的,一般可以是多對多,不過這裡只是舉例子

專案的結構,如圖:

Classes.java:

package com.mybatis.entity;

import java.util.List;

public class Classes {

	private int id;
	
	private String name;
	
	private Teacher teacher;

	private List<Student> students;
	
	public List<Student> getStudents() {
		return students;
	}

	public void setStudents(List<Student> students) {
		this.students = students;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	
	@Override
	public String toString() {
		return "Classes [id=" + id + ", name=" + name + "]";
	}
	
}

Teacher.java:

package com.mybatis.entity;

public class Teacher {
	
	private int id;
	
	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	

}

這裡以兩種方式進行使用

classesMapper.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,namespace的值習慣上設定成包名+sql對映檔名,這樣就能夠保證namespace的值是唯一的 
-->
<mapper namespace="com.mybatis.mapper.classesMapper">

<!-- 
	在select標籤中編寫查詢的SQL語句, 設定select標籤的id屬性為findById,id屬性值必須是唯一的,不能夠重複
    parameterType可以在MyBatis的配置檔案裡設定,也可以直接用包名+類名
 -->
 
	<select id="findById" parameterType="int" resultMap="ClassesResultMap">
	select * from classes c,teachers t where c.teacher_id=t.t_id and c.c_id=#{id}
	</select>
	<resultMap type="Classes" id="ClassesResultMap">
		<id property="id" column="c_id" />
		<result property="name" column="c_name" />
		<association property="teacher" column="teacher_id" javaType="Teacher">
			<id property="id" column="t_id" />
			<result property="name" column="t_name" />
		</association>
	</resultMap>
	
	<select id="findById2" parameterType="int" resultMap="ClassesResultMap2">
	select * from classes where c_id=#{id}
	</select>
	<resultMap type="Classes" id="ClassesResultMap2">
		<id property="id" column="c_id" />
		<result property="name" column="c_name" />
		<association property="teacher" column="teacher_id" javaType="Teacher" select="getTeacherInfo">
		</association>
	</resultMap>
	<select id="getTeacherInfo" parameterType="int" resultType="Teacher">
	select t_id,t_name from teachers where t_id=#{id}
	</select>
</mapper>

然後對mybatis進行配置:

<?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>
	
	<!-- 資料庫配置檔案  --> 
    <properties resource="db.properties" />  
     
   <!-- 實體類,簡稱 -設定別名 -->
	<typeAliases>
		<typeAlias alias="User" type="com.mybatis.entity.User" />
		<typeAlias alias="Classes" type="com.mybatis.entity.Classes" />
		<typeAlias alias="Student" type="com.mybatis.entity.Student" />
		<typeAlias alias="Teacher" type="com.mybatis.entity.Teacher" />
	</typeAliases>

	
	<!-- 讀取db.properties裡的資料,進行資料庫配置 -->
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}"/>
	            <property name="url" value="${url}" />
	            <property name="username" value="${username}"/>
	            <property name="password" value="${password}"/>
			</dataSource>
		</environment>
	</environments>
	
	<!--  
		註冊userMapper.xml檔案 
	<mappers>
		<mapper resource="com/mybatis/mapper/userMapper.xml"/>
	</mappers>
	-->
	
	<mappers>
		<mapper class="com.mybatis.mapper.UserMapper"/>
		<mapper resource="com/mybatis/mapper/classesMapper.xml"/>
	</mappers>
	
</configuration>

db,properties:

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/db_mysql?useUnicode\=true&characterEncoding\=utf-8
username=root
password=111



編寫測試類:

String resource = "mybatis-config.xml";
		try{
			//載入Mybatis的配置檔案
			Reader reader = Resources.getResourceAsReader(resource);
			//構建sqlSession的工廠
	        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
			//建立可以執行sql的SqlSession
	        SqlSession session = sessionFactory.openSession();
			UserMapper mapper = session.getMapper(UserMapper.class);
			User user = mapper.findById(1);
	        System.out.println(user);
	        
	        Classes c = session.selectOne("com.mybatis.mapper.classesMapper.findById1",1);
	        System.out.println(c);
	      
	        
		}catch (Exception e) {
			e.printStackTrace();
		}