使用 myBatis 使用 JOIN 查询获取一对一关系对象

Get one-to-one relationship objects with JOIN query with myBatis

我尝试使用 MyBatis 从数据库对象中获取,其中有另一个对象作为字段。像这样:

public class Worker {
  private int id;
  private String firstName;
  private String lastName;

  private Bank bank;   
}

public class Bank  {
  private int id;
  private String name;
}

可以看出,这里应该是一对一的关系。 目前我只找到两个解决方案:

1) 引用银行sql给WorkerMapper添加@Result注解,像这样:

public interface WorkerMapper {
  @Results({
    @Result(column = "id",          property = "id"),
    @Result(column = "first_name",  property = "firstName"),
    @Result(column = "last_name",   property = "lastName"),
    @Result(property="bank", javaType=Bank.class, column="id", many=@Many(select="getBank"))
  })
  @Select("worker select")
  Worker get(int id);

  @Select("bank select")
  Bank getBank(int id);
)

但是,如果我理解正确的话,如果我这样做,我需要为银行和工人执行两个查询^。这对BD来说不是很好

2) 我可以用 "inner join" 编写 sql 查询,创建一些 "RowAdapter" class,其中包含所有查询字段。从数据库中获取后,我将解析我需要的对象。 这种方案比两次查询要好,但是需要写很多代码。

在 MyBatis 中使用 "inner join" 一次 sql 查询获取两个对象是否有更优雅的解决方案(最好使用注释)?

请注意,使用 @Many 涉及 Worker class 有 Collection<Bank> 属性。在你的情况下,你必须使用 @One.

只是引用 API documentation:

@One: A mapping to a single property value of a complex type. Attributes: select, which is the fully qualified name of a mapped statement (i.e. mapper method) that can load an instance of the appropriate type,

多个查询的潜在兴趣是lazyLoading及时获取银行日期。

fetchType, which supersedes the global configuration parameter lazyLoadingEnabled for this mapping.

这其实取决于你的要求。

  • 如果按 ID 限制为 select 工作人员,则按 ID select 银行, 2个简单查询和单个查询之间没有太大区别 加入查询。

  • 如果你select所有工人(比如说100万),那么100万 select-可以发行银行。如果懒惰,则 JOIN 查询可能更可取 加载不是一个选项。

无论如何,

NOTE You will notice that join mapping is not supported via the Annotations API. This is due to the limitation in Java Annotations that does not allow for circular references.

然后在XML中定义结果映射是JOIN查询所必需的。使用自动映射,以下内容应该足够了:

<resultMap id ="workerResultMap" type="Worker">
  <association property="bank" resultMap="bankResultMap"/>
</resultMap>
<resultMap id ="bankResultMap" type="Bank">
</resultMap>