mybatis關聯映射一對一

在項目開發中,會存在一對一的關係,好比一我的只有一個身份證,一個身份證只能給一我的使用,這就是一對一關係。一對一關係使用主外鍵關聯。

table.sql,在數據庫中建立以下兩個表並插入數據java

CREATE TABLE T_CARD(
    ID INT PRIMARY KEY AUTO_INCREMENT,
    CODE VARCHAR(20)
);
INSERT INTO T_CARD(CODE)VALUES('130113198701274657');

CREATE TABLE T_PERSON(
    ID INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAR(20) DEFAULT NULL,
    SEX CHAR(20) DEFAULT NULL,
    AGE INT(11) DEFAULT NULL,
    CARD_ID INT UNIQUE,
 FOREIGN KEY(CARD_ID) REFERENCES T_CARD(ID)
);
INSERT INTO T_PERSON(NAME,SEX,AGE,CARD_ID) VALUES('張三','男','23',1);

mybatis-config.xmlmysql

<?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>
    <!-- 指定 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="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.47.151:3306/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  <!-- mappers告訴了MyBatis去哪裏找持久化類的映射文件 -->
  <mappers>
    <mapper resource="mapper/CardMapper.xml"/>
    <mapper resource="mapper/PersonMapper.xml"/>
  </mappers>
</configuration>

PersonMapper.xmlsql

<?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">
<!-- namespace指用戶自定義的命名空間。 -->
<mapper namespace="com.rookie.bigdata.mapper.PersonMapper">


    <parameterMap type="com.rookie.bigdata.domain.Person" id="parameterPersonMap">
        <parameter property="id"/>
        <parameter property="name"/>
        <parameter property="sex"/>
        <parameter property="age"/>
    </parameterMap>

    <insert id="insertPerson" parameterMap="parameterPersonMap">
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            SELECT LAST_INSERT_ID() AS ID
        </selectKey>
        INSERT INTO t_person(name,sex,age,card_id)
        VALUES(#{name},#{sex},#{age},#{card.id})    <!--記得不要有逗號-->
    </insert>

    <!-- 根據id查詢Person,返回resultMap -->
    <select id="selectPersonById" parameterType="int"
            resultMap="personMapper">
    SELECT * from t_person where id = #{id}
  </select>

    <!-- 映射Peson對象的resultMap -->
    <resultMap type="com.rookie.bigdata.domain.Person" id="personMapper">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="sex" column="sex"/>
        <result property="age" column="age"/>
        <!-- 一對一關聯映射:association   -->
        <association property="card" column="card_id"
                     select="com.rookie.bigdata.mapper.CardMapper.selectCardById"
                     javaType="com.rookie.bigdata.domain.Card"/>
    </resultMap>

</mapper>

CardMapper.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">
<!-- namespace指用戶自定義的命名空間。 -->
<mapper namespace="com.rookie.bigdata.mapper.CardMapper">

    <!-- 根據id查詢Card,返回Card對象 -->
    <select id="selectCardById" parameterType="int" resultType="com.rookie.bigdata.domain.Card">
    SELECT * from t_card where id = #{id}
  </select>

    <parameterMap type="com.rookie.bigdata.domain.Card" id="cardMap">
        <parameter property="id"/>
        <parameter property="code"/>
    </parameterMap>

    <insert id="insertCard" parameterMap="cardMap">
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            SELECT LAST_INSERT_ID() AS ID
        </selectKey>
        INSERT INTO T_CARD(id,code)
        VALUES(?,?)
    </insert>


</mapper>

Card.javaapache

public class Card implements Serializable {
    
    private Integer id;  // 主鍵id
    private String code; // 身份證編號
}

Person.javasession

public class Person implements Serializable {

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

CardMapper.javamybatis

public interface CardMapper {

    void insertCard(Card card);

}

PersonMapper.javaapp

public interface PersonMapper {

    /**
     * 根據id查詢Person
     */
    Person selectPersonById(Integer id);


    /**
     * 插入數據
     * @param person
     */
    void insertPerson(Person person);

}

SqlSessionFactoryUtil.javadom

package com.rookie.bigdata.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;

public class SqlSessionFactoryUtil {
    
    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;
    }

}

測試代碼進行增查操做測試

package com.rookie.bigdata.test;


import com.rookie.bigdata.domain.Card;
import com.rookie.bigdata.domain.Person;
import com.rookie.bigdata.mapper.CardMapper;
import com.rookie.bigdata.mapper.PersonMapper;
import com.rookie.bigdata.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.Test;


public class OneToOneTest {

    @Test
    public  void test() throws Exception {
        // 建立Session實例
        SqlSession session = SqlSessionFactoryUtil.getSqlSession();

        // 得到mapper接口的代理對象
        PersonMapper pm = session.getMapper(PersonMapper.class);
        // 直接調用接口的方法,查詢id爲1的Peson數據
        Person p = pm.selectPersonById(1);
        // 打印Peson對象
        System.out.println(p);
        // 打印Person對象關聯的Card對象
        System.out.println(p.getCard());

        // 提交事務
        session.commit();
        // 關閉Session
        session.close();
    }

    @Test
    public void test1() throws Exception {
        SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Transaction tx = transactionFactory.newTransaction(sqlSession
                .getConnection());

        Card card = new Card();
        card.setCode("130442154542048521");

        Person person = new Person();
        person.setName("lisi");
        person.setSex("男");
        person.setAge(30);
        person.setCard(card);


        PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
        CardMapper cardMapper = sqlSession.getMapper(CardMapper.class);

        cardMapper.insertCard(card);
        personMapper.insertPerson(person);

        System.out.println(card.getId());

       tx.commit();


    }


}

進行測試完美解決

相關文章
相關標籤/搜索