经常使用类似 left join 做查询,偶尔遇到两张表的字段名相同(即 column 名字一致),此时可以在 mybatis 中这样配置
例子:
<select id="demo" resultMap="DemoResultMap"> | |
SELECT DISTINCT | |
t1.username, | |
t1.password, | |
t2.username "t2_username", | |
t2.age | |
FROM table1 t1 | |
LEFT JOIN table2 t2 | |
ON t1.id = t2.id | |
WHERE t1.age = #{age,jdbcType=VARCHAR} | |
</select> | |
<resultMap id="DemoResultMap" type="com.demo.vo.UserVo" > | |
<id column="id" property="id" jdbcType="VARCHAR"/> | |
<result column="username" property="username" jdbcType="VARCHAR"/> | |
<result column="password" property="password" jdbcType="VARCHAR"/> | |
<result column="t2_username" property="t2Username" jdbcType="VARCHAR"/> | |
<result column="age" property="age" jdbcType="VARCHAR"/> | |
</resultMap> |
table1 表和 table2 表都包含一个 username 字段,但实体中字段名是不同的,当联表查询时,可以起一个别名 t2_username 做转换,然后通过实体接收即可。
参考:https://www.cnblogs.com/hupi/p/5656742.html