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反射技術,如果列名和實體類字段名不同,則反射不成功。