Mybatis配置文件resultMap映射啥时候可写可不写?


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>


3、students表结构 2 字段名与实体类字段名 不同

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_sal
		from students
		where students_id = #{xxxxxxxxxxxxxxxxxx}
</select>


3、为什么相同可不写,不同必须写?

因为用了java反射技术,如果列名和实体类字段名不同,则反射不成功。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

松门一枝花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值