在 MyBatis 中,你可以在 XML 映射文件中編寫 SQL 語句,然后使用 UNION ALL 關鍵字來進行多表查詢。下面是一個簡單的示例:
CREATE TABLE table_a (
id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE table_b (
id INT PRIMARY KEY,
name VARCHAR(255)
);
<?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="com.example.mapper.UnionAllMapper">
<resultMap id="unionAllResultMap" type="com.example.model.UnionAllResult">
<result property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
<select id="getUnionAllData" resultMap="unionAllResultMap">
SELECT id, name FROM table_a
UNION ALL
SELECT id, name FROM table_b
</select>
</mapper>
package com.example.model;
public class UnionAllResult {
private int id;
private String name;
// Getters and setters
}
package com.example.mapper;
import com.example.model.UnionAllResult;
import java.util.List;
public interface UnionAllMapper {
List<UnionAllResult> getUnionAllData();
}
現在,你可以在你的服務類中調用 getUnionAllData()
方法來獲取兩個表的合并數據。