是否可以在一个查询中使用MyBatis将嵌入对象与注释映射,例如:
Foo类:
public class Foo //immutable
{
private final Integer fooId;
private final String fooAttr;
private final Bar bar;
public Foo(Integer fooId, String fooAttr, Bar bar) //constructor
}
public class Foo //immutable
{
private final Integer fooId;
private final String fooAttr;
private final Bar bar;
public Foo(Integer fooId, String fooAttr, Bar bar) //constructor
}
酒吧班:
表FooBar:
public class Bar { //immutable
private final Integer barId;
private final String barAttr;
public Bar(Integer barId, String barAttr) //constructor
}
public class Bar { //immutable
private final Integer barId;
private final String barAttr;
public Bar(Integer barId, String barAttr) //constructor
}
查询:
- INT foo_id
- CHAR foo_attr
- INT bar_id
- CHAR bar_attr
- INT foo_id
- CHAR foo_attr
- INT bar_id
- CHAR bar_attr
如何将Bar类映射为Foo构造函数参数(不使用子查询)?
答案 0 :(得分:2)
我知道,这很痛苦,但以下情况可行:
@ConstructorArgs({
@Arg(column="foo_id", javaType=Integer.class),
@Arg(column="foo_attr", javaType=String.class),
@Arg(column="bar_id", javaType=Integer.class),
@Arg(column="bar_attr", javaType=String.class)
})
构造函数应该如下所示:
public Foo(Integer fooId, String fooAttr, Integer barId, String barAttr)
this.fooId = fooId;
this.fooAttr = fooAttr;
this.bar = new Bar(barId, barAttr);
}
如果未设置ID,您甚至可以将栏留空:
public Foo(Integer fooId, String fooAttr, Integer barId, String barAttr)
this.fooId = fooId;
this.fooAttr = fooAttr;
if (barId != null) {
this.bar = new Bar(barId, barAttr);
}
}