1. 程式人生 > >MyBatis框架基於Annotation註解的一對一關聯對映

MyBatis框架基於Annotation註解的一對一關聯對映

 程式碼:

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">
  <!--  XML 配置檔案包含對 MyBatis 系統的核心設定 -->
<configuration>
	<properties resource="db.properties"/>
	<!-- 指定 MyBatis 所用日誌的具體實現 -->
	<settings>
		<setting name="logImpl" value="LOG4J"/>
	</settings>
	
	<environments default="mysql">
	<!-- 環境配置,即連線的資料庫。 -->
    <environment id="mysql">
    <!--  指定事務管理型別,type="JDBC"指直接簡單使用了JDBC的提交和回滾設定 -->
      <transactionManager type="JDBC"/>
      <!--  dataSource指資料來源配置,POOLED是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> 
  
  <!-- mappers告訴了MyBatis去哪裡找持久化類的對映檔案 -->
  <mappers>
  	<mapper class="com.mapper.PersonMapper"/> 
  	<mapper class="com.mapper.CardMapper"/> 
  </mappers>
</configuration>

Card.java
package com.bean;

import java.io.Serializable;

public class Card implements Serializable {
	private Integer id;  // 主鍵id
	private String code; // 身份證編號
	public Card() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "Card [id=" + id + ", code=" + code + "]";
	}
	
}

Person.java
package com.bean;

import java.io.Serializable;

public class Person implements Serializable {
	private Integer id;  // 主鍵id
	private String name; // 姓名
	private String sex;  // 性別
	private Integer age; // 年齡
	
	// 人和身份證是一對一的關係,即一個人只有一個身份證
	private Card card;

	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Card getCard() {
		return card;
	}

	public void setCard(Card card) {
		this.card = card;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "Person [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
	} 
	
}

FKSqlSessionFactory.java
package com.factory;

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 FKSqlSessionFactory {
	
	private static SqlSessionFactory sqlSessionFactory = null;
	
	// 初始化建立SqlSessionFactory物件
	static{
		try {
			// 讀取mybatis-config.xml檔案
			InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder()
					.build(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 獲取SqlSession物件的靜態方法
	public static SqlSession getSqlSession(){
		return sqlSessionFactory.openSession();
	}

	// 獲取SqlSessionFactory的靜態方法
	public static SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

}

CardMapper.xml
package com.mapper;

import org.apache.ibatis.annotations.Select;

import com.bean.Card;

public interface CardMapper {
	@Select("select * from tb_card where id = #{id} ")
	Card selectCardById(Integer id);
}

PersonMapper.xml
package com.mapper;

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

import com.bean.Person;

public interface PersonMapper {
	@Select("select * from tb_person where id = #{id}")
	@Results({
		@Result(id=true,column="id",property="id"),
		@Result(column="name",property="name"),
		@Result(column="sex",property="sex"),
		@Result(column="age",property="age"),
		@Result(column="card_id",property="card",one=@One(
				select="com.mapper.CardMapper.selectCardById",fetchType=FetchType.EAGER))
	})
	Person selectPersonById(Integer id);
}

OneToOneTest.java
package com.test;

import org.apache.ibatis.session.SqlSession;

import com.bean.Person;
import com.factory.FKSqlSessionFactory;
import com.mapper.PersonMapper;

public class OneToOneTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
       SqlSession session=FKSqlSessionFactory.getSqlSession();
       // 獲取PersonMapper例項
       PersonMapper pm = session.getMapper(PersonMapper.class);
       // 根據id查詢Person物件,同時需要獲得關聯的Card物件
       Person p = pm.selectPersonById(1);
       System.out.println(p);
	   // 檢視查詢到的關聯的Card物件
	   System.out.println(p.getCard());
	   session.commit();
	   session.close();
	}

}

截圖: