Mybatis之@ResultMap,@Results,@Result注解的使用

2022-07-20,,,,

目录
  • mybatis注解@results、@result、@resultmap
    • 问题
    • 方法一
    • 方法二
  • mybatis注释使用
    • resultmap对应的注释,及对应注解results、result、one、many的使用
    • 1.@results注解
    • 2.@resutl注解
    • 3.@one注解(一对一)
    • 4.@many注解(多对一)

mybatis注解@results、@result、@resultmap

问题

在使用mybatis时发现,mybatis能自动匹配实体名和数据库字段名相同的字段。当有实体名与数据库的字段名不同时该如何解决??

数据库的表对应的列名:

springboot项目中建的实体类为:

public class mapmodel {
    private long key;
    private string value;
    
    //省略getter、setter方法
    }

方法一

给查询字段另起名对应实体类的名称:

@select("select province_id as key , province_name as value from `j_position`")
public list<mapmodel> provincename();

方法二

使用@results、@result、@resultmap注解:

@select("select province_id, province_name from `j_position`")
    @results(id="resultmap1" ,value = {
            @result(property = "key",column = "province_id"),
            @result(property = "value",column ="province_name")
    })
public list<mapmodel> provincename();

其中定义的id="resultmap1"可以使用

@resultmap("resultmap1)
@select("select province_id, province_name from `j_position` where province_name=#{name}")
public list<mapmodel> provincename(string name);

推荐使用方法二!

mybatis注释使用

resultmap对应的注释,及对应注解results、result、one、many的使用

有一部分建立在我上一个博客,mybatis注释使用(单表查询),如果那里看不懂了,建议看下我上一个博客(里面所有的配置文件,接口,数据库的创建都有说明)

<resultmap>对应的注解:

1.@results注解

代替的是标签<resultmap >

该注解中可以使用单个@result注解,也可以使用@result集合

@results({@result(),@result()})或@results(@result())

注意:使用注解是若报出org.apache.ibatis.binding.bindingexception:invalid bound statement (not found):接口全类名.方法名

可能是使用@results注解时忘记使用@select注解

2.@resutl注解

代替了 <id>标签和<result>标签

@result 中 属性介绍:

  • column 数据库的列名
  • property需要装配的属性名
  • one 需要使用的@one注解(@result(one=@one)()))
  • many 需要使用的@many注解(@result(many=@many)()))

3.@one注解(一对一)

代替了<assocation>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。

@one注解属性介绍:

  • select 指定用来多表查询的sqlmapper
  • fetchtype会覆盖全局的配置参数lazyloadingenabled。。

使用格式:

@result(column=" ",property="",one=@one(select=""))

4.@many注解(多对一)

代替了<collection>标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。

注意:聚集元素用来处理“一对多”的关系。需要指定映射的java实体类的属性,属性的javatype(一般为arraylist)但是注解中可以不定义;

使用格式:

@result(property="",column="",many=@many(select=""))

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

《Mybatis之@ResultMap,@Results,@Result注解的使用.doc》

下载本文的Word格式文档,以方便收藏与打印。