MyBatis的映射配置文件中的<resultMap>标签或该标签中的子标签<id>、<result>可省略。
一、bean中的属性名与数据库的字段名不同,无法省略<resultMap>。
User.java
public class User { private int idx; private String usernamex; private String passwordx; /*getter和setter方法省略*/ }
配置文件
在这种情况下,<resultMap>下的每一个子标签代表了一个映射关系,不能省略。<!--column为数据库列名,property为bean的属性名,两者名字不相同的情况不能省略--> <resultMap id="userMap" type="com.yykj.beans.User"> <id column="id" property="idx" jdbcType="INTEGER"/> <result column="username" property="usernamex" jdbcType="VARCHAR"/> <result column="password" property="passwordx" jdbcType="VARCHAR"/> </resultMap>
若<resultMap>下的子标签都省略了,那么会生成一个null对象,并加入映射结果的List对象中,如果有任何一个子标签存在,则会生成一个bean对象,只有未省略的那一项标签的属性值不为null,其它都为null。
二、bean中的属性名和数据库的字段名,可以省略<resultMap>下的子标签。
User.java
配置文件public class User { private int id; private String username; private String password; /*getter和setter方法省略*/ }
<resultMap>下的标签可以省略任意项,甚至可以全部省略。<resultMap id="userMap" type="com.yykj.beans.User"> <!--以下标签可以省略任意项,Mybatis会根据java反射机制自动识别。--> <!-- <id column="id" property="id" jdbcType="INTEGER"/> <result column="username" property="username" jdbcType="VARCHAR"/> <result column="password" property="password" jdbcType="VARCHAR"/>--> </resultMap>
三、bean中的属性名和数据库的字段名,可以不用<resultMap>,使用resultType替代。
MyBatis框架强大的功能都得益于Java的反射机制。<select id="selectAllUser" resultType="com.yykj.beans.User"> SELECT * FROM user </select>