首页 > 代码库 > MyBatis系列:(6)一对一映射

MyBatis系列:(6)一对一映射


0、准备SQL语句(mysql)

CREATE TABLE cards(
    cid INT(5) PRIMARY KEY,
    cnum VARCHAR(18)
);

CREATE TABLE students(
    sid INT(5) PRIMARY KEY,
    sname VARCHAR(10),
    scard_id INT(5),
    CONSTRAINT students_fk FOREIGN KEY(scard_id) REFERENCES cards(cid)
);

INSERT INTO cards(cid,cnum) VALUES(1,‘111‘);
INSERT INTO students(sid,sname,scard_id) VALUES(2,‘小明‘,1);

SELECT * FROM cards;
SELECT * FROM students;

SELECT s.sid,s.sname,c.cid,c.cnum
FROM students s INNER JOIN cards c ON s.scard_id=c.cid


2、entity类

Student.java

package com.rk.entity;

public class Student {
    private Integer id;
    private String name;
    private Card card;
    public Student(){}
    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 Card getCard() {
        return card;
    }
    public void setCard(Card card) {
        this.card = card;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", card=" + card + "]";
    }
    
}

Card.java

package com.rk.entity;

public class Card {
    private Integer id;
    private String num;
    private Student student;
    public Card(){}
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getNum() {
        return num;
    }
    public void setNum(String num) {
        this.num = num;
    }
    public Student getStudent() {
        return student;
    }
    public void setStudent(Student student) {
        this.student = student;
    }
    @Override
    public String toString() {
        return "Card [id=" + id + ", num=" + num + "]";
    }
    
}


3、mybatis的映射文件

CardMapp.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="cardNamespace">
    <resultMap type="com.rk.entity.Card" id="cardMap">
        <id property="id" column="cid"/>
        <result property="num" column="cnum"/>
    </resultMap>
</mapper>

StudentMapper.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="studentNamespace">
    <resultMap type="com.rk.entity.Student" id="studentMap">
        <id property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="card" resultMap="cardNamespace.cardMap"></association>
    </resultMap>
    <select id="findById" parameterType="int" resultMap="studentMap">
        select s.sid,s.sname,c.cid,c.cnum
        from students s inner join cards c on s.scard_id=c.cid
        and s.sid=#{id}
    </select>
</mapper>


4、mybatis主配置包含映射文件

mybatis.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">
<configuration>
    <properties resource="db.properties"></properties>
    <typeAliases>
        <typeAlias type="com.rk.entity.Emp" alias="emp"/>
    </typeAliases>
    <environments default="mysql_developement">
        <environment id="mysql_developement">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="http://www.mamicode.com/${mysql.driver}"/>
                <property name="url" value="http://www.mamicode.com/${mysql.url}"/>
                <property name="username" value="http://www.mamicode.com/${mysql.username}"/>
                <property name="password" value="http://www.mamicode.com/${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/rk/entity/CardMapper.xml"/>
        <mapper resource="com/rk/entity/StudentMapper.xml"/>
    </mappers>
</configuration>


db.properties

mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/testdb
mysql.username=root
mysql.password=root


5、MyBatisUtils.java

package com.rk.utils;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

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 {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    private MyBatisUtils(){}
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession == null){
            sqlSession = sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }
    
    public static void closeSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            sqlSession.close();
            threadLocal.remove();
        }
    }
    
    public static void main(String[] args) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        Connection conn = sqlSession.getConnection();
        System.out.println(conn);
    }
}


6、StudentCardDao.java

package com.rk.dao;

import org.apache.ibatis.session.SqlSession;

import com.rk.entity.Student;
import com.rk.utils.MyBatisUtils;

public class StudentCardDao {
    
    public Student findById(int id){
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.getSqlSession();
            Student stu = sqlSession.selectOne("studentNamespace.findById", id);
            return stu;
        }
        catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
        finally{
            MyBatisUtils.closeSqlSession();
        }
    }
    
    public static void main(String[] args) {
        StudentCardDao dao = new StudentCardDao();
        Student stu = dao.findById(2);
        System.out.println(stu);    
    }
}


MyBatis系列:(6)一对一映射