如何在 RowMapper class 中包含内部列表
how can I iclude an inner list in a RowMapper class
我有一个关于 Spring JDBC RowMapper 组织的问题。
假设我有一个 table a
,字段为 id
和 name
、table a_b
和 table b
.
a
id integer
name character varying (16)
b
id integer
name character varying (16)
a_b
a_b_id integer
aid integer
bid integer
Class结构不是那么对称:
class A{
int id;
String name;
List<B> bs;
}
class B{
int id;
String name;
}
我想为 class A 构造一个 RowMapper class。开始代码如下:
class AMapper implements RowMapper<A>{
public A mapRow(ResultSet rs, int num){
A a = new A();
a.setId(rs.getInt("id"));
a.setName(rs.getString("name"));
return a;
}
}
如何映射 b
的列表?有没有办法在没有 in-mapper sql 查询的情况下获取它?
如果你想通过单个查询获取它们,你将不得不使用 JOIN 从多个表中获取(无论你使用 LEFT join 还是 INNER 这取决于你想要实现的目标)这将 return 你是一个组合列的矩阵,在 ResultSet 中是这样的:
a_id | a_name | b_id | b_name | ...
------------------------------------
1 | Name1A | 1 | Name1B | ...
1 | Name1A | 2 | Name2B | ...
1 | Name1A | 3 | Name3B | ...
虽然您有 1 个 A 记录,但它与多个 B 相关联,并且会出现在每一行中。
您需要通过 Map 或 Set 跟踪 A。像这样的东西(你可能需要调整它):
class AMapper implements RowMapper<A> {
Map<Integer, A> aMap = new HashMap<>();
public A mapRow(ResultSet rs, int num){
A a = aMap.get(rs.getInt("id"));
if(a == null){
a = new A();
a.setId(rs.getInt("a_id"));
a.setName(rs.getString("a_name"));
aMap.put(a.getId(), a);
}
B b = new B();
b.setId(rs.getInt("b_id");
b.setName(rs.getString("b_name"));
a.addB(b);
}
}
我有一个关于 Spring JDBC RowMapper 组织的问题。
假设我有一个 table a
,字段为 id
和 name
、table a_b
和 table b
.
a
id integer
name character varying (16)
b
id integer
name character varying (16)
a_b
a_b_id integer
aid integer
bid integer
Class结构不是那么对称:
class A{
int id;
String name;
List<B> bs;
}
class B{
int id;
String name;
}
我想为 class A 构造一个 RowMapper class。开始代码如下:
class AMapper implements RowMapper<A>{
public A mapRow(ResultSet rs, int num){
A a = new A();
a.setId(rs.getInt("id"));
a.setName(rs.getString("name"));
return a;
}
}
如何映射 b
的列表?有没有办法在没有 in-mapper sql 查询的情况下获取它?
如果你想通过单个查询获取它们,你将不得不使用 JOIN 从多个表中获取(无论你使用 LEFT join 还是 INNER 这取决于你想要实现的目标)这将 return 你是一个组合列的矩阵,在 ResultSet 中是这样的:
a_id | a_name | b_id | b_name | ...
------------------------------------
1 | Name1A | 1 | Name1B | ...
1 | Name1A | 2 | Name2B | ...
1 | Name1A | 3 | Name3B | ...
虽然您有 1 个 A 记录,但它与多个 B 相关联,并且会出现在每一行中。
您需要通过 Map 或 Set 跟踪 A。像这样的东西(你可能需要调整它):
class AMapper implements RowMapper<A> {
Map<Integer, A> aMap = new HashMap<>();
public A mapRow(ResultSet rs, int num){
A a = aMap.get(rs.getInt("id"));
if(a == null){
a = new A();
a.setId(rs.getInt("a_id"));
a.setName(rs.getString("a_name"));
aMap.put(a.getId(), a);
}
B b = new B();
b.setId(rs.getInt("b_id");
b.setName(rs.getString("b_name"));
a.addB(b);
}
}