在 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()
方法来获取两个表的合并数据。