之前是默认按类属性声明顺序来对应数据库中的列,可以通过新增 resultMap 标签来自定义,而非直接用属性:

<mapper namespace="TestMapper">
    <select id="selectStudent" resultMap="Test">
        select * from student
    </select>
    <resultMap id="Test" type="Student">
        <result column="sid" property="sid"/>
        <result column="age" property="name"/>
        <result column="name" property="age"/>
    </resultMap>
</mapper>

构造方法映射问题

如果类只有一个构造方法,且其参数少于数据库中的参数,那么默认情况下仍会给能按顺序对应上的都给赋值。

public Student (int Sno) {  
    this.sno = Sno;  
}  
  
public Student(int Sno, String name) {  
    this.name = name;  
    this.sno = Sno;  
}

而如果有两个以上构造方法,就无法自动实现赋值,如果没有一个完美匹配的就会报错。此时可以通过在 resultMap 中设定构造标签 constructor 来设定一个构造方法:

    <resultMap id="Test" type="Student">
        <constructor>
            <arg column="sid" javaType="int"/>
            <arg column="name" javaType="String"/>
        </constructor>
        <result column="sid" property="sid"/>
        <result column="age" property="name"/>
        <result column="name" property="age"/>
    </resultMap>

此时,Mybatis 会把对应的查询数据传入到符合该参数的构造方法中,调用构造方法来进行属性的赋值。而对于不在该构造方法的属性,依然会按默认情况进行赋值。