MyBatis Multi-Table Association Queries

Database Schema

Company Table

Game Table

Game-Company Relationship Table

Login Table

User Information Table

Project Structure

One-to-One Relationship Queries

Retrieving User by User Information QQ

1. Entity Definition (User class with embedded User Information object)

package entity;

import java.util.List;

public class User extends Base {
    private String username;
    private String pwd;
    private UserInfo details;
    private List<Game> gameList;

    public User() {}

    public User(String username, String pwd, UserInfo details, List<Game> gameList) {
        this.username = username;
        this.pwd = pwd;
        this.details = details;
        this.gameList = gameList;
    }

    // Getters and setters
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    
    public String getPwd() { return pwd; }
    public void setPwd(String pwd) { this.pwd = pwd; }
    
    public UserInfo getDetails() { return details; }
    public void setDetails(UserInfo details) { this.details = details; }
    
    public List<Game> getGameList() { return gameList; }
    public void setGameList(List<Game> gameList) { this.gameList = gameList; }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", pwd='" + pwd + '\'' +
                ", details=" + details +
                ", gameList=" + gameList +
                '}';
    }
}

Add the user information object to the existing entity with corresponding getters, setters, constructor updates, and toString method.

2. Define resultMap

<resultMap id="UserWithDetailsMap" type="User">
    <id column="id" property="id"/>
    <result column="userName" property="username"/>
    <result column="password" property="pwd"/>
    <association property="details" resultMap="UserInfoResultMap"/>
</resultMap>

<resultMap id="UserInfoResultMap" type="UserInfo">
    <id column="id" property="id"/>
    <result column="email" property="email"/>
    <result column="qq" property="qq"/>
    <result column="uid" property="uid"/>
</resultMap>

Column represents database column names, property represents corresponding entity attributes.

3. SQL Statement

<select id="findUserAndInfoByQQ" parameterType="String" resultMap="UserWithDetailsMap">
    SELECT * FROM login l INNER JOIN userinfo u ON l.id = u.uid WHERE u.qq = #{qq}
</select>

4. DAO Layer Method Definition

User findUserAndInfoByQQ(String qq);

5. Test Implementation

SqlSessionFactory factory = BuilderSessionFactory.getSqlSessionFactory();
SqlSession session = factory.openSession();

SelectDao dao = session.getMapper(SelectDao.class);

public void executeUserQQQuery() {
    User result = dao.findUserAndInfoByQQ("123456");
    System.out.println(result);
}

Tags: MyBatis database ORM sql java

Posted on Tue, 01 Sep 2026 16:35:34 +0000 by ratebuster