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

8 篇文章 0 订阅

1、student实体类


    
    
  1. public class Student {
  2. private Integer id; //编号
  3. private String name; //姓名
  4. private Double sal; //薪水
  5. public Student(){}
  6. public Student(Integer id, String name, Double sal) {
  7. this.id = id;
  8. this.name = name;
  9. this.sal = sal;
  10. }
  11. public Integer getId() {
  12. return id;
  13. }
  14. public void setId(Integer id) {
  15. this.id = id;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. public Double getSal() {
  24. return sal;
  25. }
  26. public void setSal(Double sal) {
  27. this.sal = sal;
  28. }
  29. }

2、students表结构 1  字段名与实体类字段名相 同


    
    
  1. create table students(
  2. id int( 5) primary key,
  3. name varchar( 10),
  4. sal double( 8, 2)
  5. );


2.1、resultMap 映射代码


    
    
  1. <mapper namespace="studentNamespace">
  2. <resultMap type="mybatis.hello.Student" id="studentMap">
  3. <id property="id" column="id"/>
  4. <result property="name" column="name"/>
  5. <result property="sal" column="sal"/>
  6. </resultMap>
  7. </mapper>


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


    
    
  1. create table students(
  2. students_id int( 5) primary key,
  3. students_name varchar( 10),
  4. students_sal double( 8, 2)
  5. );


3.1、resultMap 映射代码


    
    
  1. <mapper namespace="studentNamespace">
  2. <resultMap type="mybatis.hello.Student" id="studentMap">
  3. <id property="id" column="students_id"/>
  4. <result property="name" column="students_name"/>
  5. <result property="sal" column="students_sal"/>
  6. </resultMap>
  7. </mapper>


1、可不写

当实体属性与表字段名相同的时候,即上面的1和2的情况,2.1resultMap映射代码可不写。

select时,返回用 resultType 


    
    
  1. <select id="findById" parameterType="int" resultType="mybatis.hello.Student">
  2. select id,name,sal from students where id = #{id}
  3. </select>

2、必须写

当实体属性与表字段名不同的时候,即上面的1和3的情况,3.1resultMap映射代码必须写。

select时,返回用 resultMap 


    
    
  1. <select id="findById" parameterType="int" resultMap="studentMap">
  2. select students_id,students_name,students_sal
  3. from students
  4. where students_id = #{xxxxxxxxxxxxxxxxxx}
  5. </select>


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

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




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值