MyBatis 一對一關係

引入架包


配置文件

數據庫配置文件



配置MyBatisConfig文件

<?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"></properties>
	<!-- 配置別名(即在mapper配置文件用到類時的名字),這裏設置類的別名即爲類的名稱 -->
	<typeAliases>
		<package name="com.mingde.po"/>
	</typeAliases>
	<!-- 配置開發環境 -->
	<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>
	<!-- 引入映射SQL語句文件 -->
	<mappers>
		<!-- 引入指定的SQL語句mapper映射文件 -->
		<mapper resource="com\mingde\mapper\mapper.xml" />
		<!-- 引入整個包所有的SQL語句mapper映射文件 -->
		<!-- <package name="com.mingde.mapper"/> -->
	</mappers>
	
</configuration>

配置MybatisUtils (SqlSessionFactory工廠)

package com.mingde.utils;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtils {

	//加載引入資源文件,創建工廠(該工廠內部會解析MyBatis配置文件,根據數據庫配置,別名配置和mapper的sql映射文件,去找到該映射文件去執行SQL語句)
	private static SqlSessionFactory getSqlSessionFactory()throws Exception{
		//利用流的方式將MyBatis配置文件引入,然後根據配置文件的內容創建工廠
		InputStream inputStram = Resources.getResourceAsStream("myBatisConfig.xml");
		//將MyBatis配置文件已流方式引,創建SqlSession工廠
		return  new SqlSessionFactoryBuilder().build(inputStram); 
	}
	
	//打開該工廠,進行運行操作;(後面加上參數:‘true’,表示當執行增刪改時自動commit提交,這樣就不用每次都手動session.commit()去提交)
	//若後面的參數不寫,則默認爲false,得每次自己手動去session.commit()提交;
	public static SqlSession getSqlSession()throws Exception{
		return getSqlSessionFactory().openSession(true);
	}
	
	
}


Mapper配置文件(見下方各個方法的不同配置)


方法一:繼承關係

實體類




Mapper.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="test">
	<!-- 查詢所有的員工並同時將其關聯的身份ID查詢出來 -->
	<!-- 方法一:【一對一關聯】  使用自定義類Employee -->
	<select id="seeAll" resultType="Employee">
		select * from employee e,idcard i where e.eid=i.id
	</select>
</mapper>

測試類

	public static void main(String[] args) throws Exception {
		//引用已打開準備好的工廠
		SqlSession session = MyBatisUtils.getSqlSession();
		//調用mapper.xml的方法,調用的方式爲:mapper.xml文件裏的‘namespace的值+id的值’,如:test.seeAll
		List<Object> selectList = session.selectList("test.seeAll");
		System.out.println(selectList);
		//關閉session
		session.close();
	}

運行結果





方法二:一對一關聯關係

實體類:

public class Employee {

	private int eid; 
	private String ename; 
	private String sex; 
	private int age; 
	private String birth;

public class IdCard {
	private int id ;
	private String card;
	private String guoji;
	
	private Employee emp;	//一對一關係

Mapper.xml配置

<!-- 方法二: -->
	<!-- 定義ResultMap -->
	<resultMap type="IdCard" id="IdCards">
		<id column="id" property="id" />
		<result column="card" property="card" />
		<result column="guoji" property="guoji" />
		<!-- 映射關聯屬性 emp-->
		<association property="emp" javaType="Employee">
			<id column="eid" property="eid" />
			<result column="ename" property="ename" />
			<result column="sex" property="sex" />
			<result column="age" property="age" />
			<result column="birth" property="birth" />
		</association>
	</resultMap>
	<!-- 查詢所有 -->
	<select id="seeAll2" resultMap="IdCards">
		select * from idCard c ,Employee e where e.eid=c.id
	</select>
	<!-- 根據id查詢 -->
	<select id="findOne2"  resultMap="IdCards">
		select * from idCard c ,Employee e where e.eid=c.id and id=#{value}
	</select>


測試類

	@Test
	public void test2() throws Exception {
		SqlSession session = MyBatisUtils.getSqlSession();
		List<Object> list = session.selectList("test.seeAll2");
		System.out.println(list);
		Object object = session.selectOne("test.findOne2", 1001);
		System.out.println(object);
	}

運行結構:




方法三:一對一關聯關係:延遲加載(建議用該方法,較實用)

實體類與方法二的一致(一對一關聯關係,一個類中的屬性定義另一個類)

Mapper.xml配置

	<!-- 方法三:延遲加載 -->
	<resultMap type="IdCard" id="IdCards3">
		<id column="id" property="id"/>
		<!-- 映射關聯屬性 emp -->
		<!-- 下面的映射的條件是進入select方法進行該定義的方法查,然後返回對象,查詢的參數爲column的內容,一旦用該方法的話,默認的是懶加載 fetchType="lazy",該條件可寫可不寫 -->
		<!-- 實現對用戶信息進行延遲加載 select:指定延遲加載需要執行的方法 ,column爲列的外建-->
		<association property="emp" javaType="Employee" column="id" select="findID" />
	</resultMap>
	<!-- 上面懶加載的方法 -->
	<select id="findID" resultType="Employee" parameterType="int" >
		select * from Employee where eid=#{value}
	</select>
	
	<!-- 查詢所有 -->
	<select id="seeAll3" resultMap="IdCards3">
		select * from idCard 
	</select>
	<!-- 根據id查詢 -->
	<select id="findOne3" resultMap="IdCards3" parameterType="int">
		select * from idCard c where id=#{value}
	</select>

測試類

	//方法三測試
	@Test
	public void test3() throws Exception {
		SqlSession session = MyBatisUtils.getSqlSession();
		List<Object> list = session.selectList("test.seeAll3");
		System.out.println(list);
		Object object = session.selectOne("test.findOne3", 1001);
		System.out.println(object);
	}

運行結果:




方法四:註解(註解不用定義Mapper.xml配置文件)

定義接口

package com.mingde.dao;

import java.util.List;

import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;


import com.mingde.po.IdCard;


public interface IdCardDao {
	
	//查詢所有
	@Select("select * from idCard ")
	//在註解中定義ResultMap
	@Results(id="IdCards",value={
			@Result(column="id",property="id"),
			@Result(column="card",property="card"),
			@Result(column="guoji",property="guoji"),
			@Result(property="emp",column="id",one=@One(select="com.mingde.dao.EmpDao.findEmp",fetchType=FetchType.LAZY))
			//上面的select寫對應的類的方法
	})
	public List<IdCard> SeeAll() throws Exception;
	
	
	//根據id查詢單個對象
	@Select("select * from idCard whereid=#{value} ")
	@ResultMap("IdCards") //使用上面定義好的ResultMap方法
	public IdCard findIdCardById(int id)throws Exception;
}

package com.mingde.dao;

import org.apache.ibatis.annotations.Select;

import com.mingde.po.Employee;

public interface EmpDao {

	
	@Select("select * from Employee where eid=#{value}")
	public Employee findEmp(int eid)throws Exception;
	
}

測試類

	//方法四測試
	@Test
	public void test4() throws Exception {
		SqlSession session = MyBatisUtils.getSqlSession();
		IdCardDao mapper = session.getMapper(IdCardDao.class);
		List seeAll = mapper.SeeAll();
		System.out.println(seeAll);
		IdCard obj = mapper.findIdCardById(1001);
		System.out.println(obj);
	}

運行結果




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章