1、student实体类
public class Student {private Integer id;//编号private String name;//姓名private Double sal;//薪水public Student(){}public Student(Integer id, String name, Double sal) {this.id = id;this.name = name;this.sal = sal;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Double getSal() {return sal;}public void setSal(Double sal) {this.sal = sal;}
}
2、students表结构 1 字段名与实体类字段名相 同
create table students(id int(5) primary key,name varchar(10),sal double(8,2)
);
2.1、resultMap 映射代码
<mapper namespace="studentNamespace"> <resultMap type="mybatis.hello.Student" id="studentMap"><id property="id" column="id"/><result property="name" column="name"/><result property="sal" column="sal"/></resultMap></mapper>
create table students(students_id int(5) primary key,students_name varchar(10),students_sal double(8,2)
);
3.1、resultMap 映射代码
<mapper namespace="studentNamespace"> <resultMap type="mybatis.hello.Student" id="studentMap"><id property="id" column="students_id"/><result property="name" column="students_name"/><result property="sal" column="students_sal"/></resultMap></mapper>
1、可不写
当实体属性与表字段名相同的时候,即上面的1和2的情况,2.1resultMap映射代码可不写。
select时,返回用 resultType
<select id="findById" parameterType="int" resultType="mybatis.hello.Student">select id,name,sal from students where id = #{id}</select>
2、必须写
当实体属性与表字段名不同的时候,即上面的1和3的情况,3.1resultMap映射代码必须写。
select时,返回用 resultMap
<select id="findById" parameterType="int" resultMap="studentMap">select students_id,students_name,students_salfrom studentswhere students_id = #{xxxxxxxxxxxxxxxxxx}
</select>
3、为什么相同可不写,不同必须写?
因为用了java反射技术,如果列名和实体类字段名不同,则反射不成功。