欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Mybatis 聪明地使用 @One 注解一个 SQL 联合查询语句来实现一对一的查询-映射器类。

最编程 2024-03-05 18:45:16
...

HubbyMapper:

package wjw.test.mybatisplus.master.onetoone;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

@Mapper
public interface HubbyMapper extends BaseMapper<Hubby> {
  //OneToOne一对一查询
  @Select("SELECT h.id, h.name, h.nickname, h.birthday, h.status, h.create_time, h.update_time, "
      + "w.wid w_wid, w.hid w_hid, w.name w_name, w.nickname w_nickname, w.birthday w_birthday "
      + "FROM hubby h left join wife w on h.id =w.hid where h.name =#{name}")
  @Results({
    @Result(column = "id", property = "id", id = true),                  // <1>
    @Result(column = "name",property = "name"),
    @Result(column = "nickname",property = "nickname"),
    @Result(column = "birthday",property = "birthday"),
    @Result(column = "password",property = "password"),
    @Result(column = "status",property = "status"),
    @Result(column = "create_time",property = "createTime"),
    @Result(column = "update_time",property = "updateTime"),
    @Result(property = "wife", one = @One(resultMap = "WifeMap", columnPrefix = "w_")) // <2>
  })
  List<Hubby> getHubbyList(@Param("name") String name);    

  @Select("select wid, hid, name, nickname, birthday from wife where wid=#{wid}")
  @Results(id = "WifeMap", 
    value={
      @Result(column = "wid", property = "wid", id = true),  
      @Result(column = "hid", property = "hid"),  
      @Result(column = "name",property = "name"),
      @Result(column = "nickname",property = "nickname"),
      @Result(column = "birthday",property = "birthday")
    })
  Wife getWifeById(@Param("wid")Integer wid);

}

<1>: @Result(column=“id”,property=“Id”, id = true),这个可以不写,也不会报错,但是会导致我们查询结果列表里每个实体的Id等属性没有值。

<2>: 这个@Result(property = "wife", one = @One(resultMap = "WifeMap", columnPrefix = "w_"))

property = "wife",就是Hubby类中的wife字段。

resultMap = "WifeMap" 指向getWifeById方法上的@Results注解里的id值.

事实上,getWifeById这个方法并没有被真的调用,甚至上面 Select 注解中的 SQL 语句也不会被执行。定义这个方法只是因为 @Results 注解必需要依存于一个方法,换句话来说,这个方法只是占位符而已。

columnPrefix, 会为 WifeMap中的所有列名都加上一个 w_ 前缀,这样一来就能匹配上联合查询 SQL 语句中实际返回的列名(例如 w_wid)了。

推荐阅读