表1
表2
两张表都存在name字段
xml中的配置
<?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="cn.liziy.dao.StudentDao"> <!-- 查询所有学生信息, 多表连接使用resultMap --> <select id="selectAllStu" resultMap="studentResultMap"> SELECT s.id, s.name, s.sex, s.age, class_id, c.id , c.code, c.name FROM tb_student s LEFT JOIN tb_class c ON class_id = c.id </select> <!-- 映射Student对象的resultMap --> <resultMap id="studentResultMap" type="cn.liziy.entity.Student"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="age" column="age"/> <!-- 多对一关联:association --> <association property="clazz" javaType="cn.liziy.entity.Clazz"> <id property="id" column="id"/> <result property="code" column="code"/> <result property="name" column="name"/> </association> </resultMap> </mapper>
控制台的输出
页面的json数据
clazz-name的值错误了
解决方法
<?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="cn.liziy.dao.StudentDao"> <!-- 查询所有学生信息, 多表连接使用resultMap --> <select id="selectAllStu" resultMap="studentResultMap"> SELECT s.id, s.name, s.sex, s.age, class_id, c.id cid, c.code, c.name cname FROM tb_student s LEFT JOIN tb_class c ON class_id = c.id </select> <!-- 映射Student对象的resultMap --> <resultMap id="studentResultMap" type="cn.liziy.entity.Student"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="age" column="age"/> <!-- 多对一关联:association --> <association property="clazz" javaType="cn.liziy.entity.Clazz"> <id property="id" column="cid"/> <result property="code" column="code"/> <result property="name" column="cname"/> </association> </resultMap> </mapper>
为SQL语句增加别名 关联的部分也要修改(红色部分为修改的内容)
问题解决