Implementing One-to-One Mappings in MyBatis

Database Schema Setup

Create tables for identity cards and students, where each student references one card via a foreign key.

CREATE TABLE identity_cards (
    card_id INT PRIMARY KEY,
    card_number VARCHAR(20)
);

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    student_name VARCHAR(10),
    card_ref INT,
    FOREIGN KEY (card_ref) REFERENCES identity_cards(card_id)
);

INSERT INTO identity_cards(card_id, card_number) VALUES(101, 'ID98765');
INSERT INTO students(student_id, student_name, card_ref) VALUES(1, 'Alice', 101);

Entity Clases

Define Java classes representing the data model.

public class IdentityCard {
    private int id;
    private String number;
    
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getNumber() { return number; }
    public void setNumber(String number) { this.number = number; }
}

public class Student {
    private int id;
    private String name;
    private IdentityCard identityCard;
    
    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 IdentityCard getIdentityCard() { return identityCard; }
    public void setIdentityCard(IdentityCard identityCard) { this.identityCard = identityCard; }
}

MyBatis Mapper Configuraton

Configure result mappings and SQL queries in XML mapper files.

IdentityCardMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="identityCardMapper">
    <resultMap id="cardResult" type="IdentityCard">
        <id property="id" column="card_id"/>
        <result property="number" column="card_number"/>
    </resultMap>
</mapper>

StudentMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="studentMapper">
    <resultMap id="studentResult" type="Student">
        <id property="id" column="student_id"/>
        <result property="name" column="student_name"/>
        <association property="identityCard" resultMap="identityCardMapper.cardResult"/>
    </resultMap>
    
    <select id="selectStudentWithCard" parameterType="int" resultMap="studentResult">
        SELECT s.student_id, s.student_name, 
               c.card_id, c.card_number
        FROM students s
        INNER JOIN identity_cards c ON s.card_ref = c.card_id
        WHERE s.student_id = #{studentId}
    </select>
</mapper>

MyBatis Configuraton File

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <properties resource="database.properties"/>
    
    <typeAliases>
        <typeAlias type="com.example.IdentityCard" alias="IdentityCard"/>
        <typeAlias type="com.example.Student" alias="Student"/>
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper resource="mappers/StudentMapper.xml"/>
        <mapper resource="mappers/IdentityCardMapper.xml"/>
    </mappers>
</configuration>

Java Implementation

Execute the one-to-one query using MyBatis session API.

public class StudentRepository {
    
    public Student findStudentWithCard(int studentId) {
        SqlSession session = MyBatisSessionFactory.getSession();
        try {
            return session.selectOne("studentMapper.selectStudentWithCard", studentId);
        } finally {
            session.close();
        }
    }
    
    public static void main(String[] args) {
        StudentRepository repository = new StudentRepository();
        Student student = repository.findStudentWithCard(1);
        
        System.out.println("Student ID: " + student.getId());
        System.out.println("Student Name: " + student.getName());
        System.out.println("Card Number: " + student.getIdentityCard().getNumber());
    }
}

Tags: MyBatis ORM One-to-One Mapping java database

Posted on Sun, 17 May 2026 20:36:52 +0000 by guru2k9