我有问题。我的数据库表名为“表”,看起来像这样(现在由3行组成,它们实际上是相同的实体,但是使用不同的代码)
我也有一个实体
public class Entity {
private int id;
private List<String> codes;
private String description;
//constructor + getters/setters
}
当我执行以下操作时,它会按预期工作
@Repository
class EntityRepository {
private final ResultSetExtractor<List<Entity>> resultSetExtractor =
JdbcTemplateMapperFactory
.newInstance()
.addKeys("id")
.unorderedJoin()
.newResultSetExtractor(Entity.class);
@Autowired
private NamedParameterJdbcOperations jdbcOperations;
List<Entity> getAll() {
return jdbcOperations.query(
"SELECT id, code as codes, description FROM table", resultSetExtractor);
}
}
结果:Entity[id=1, codes={"111", "222", "333"}, description="description1"]
但是
当我向这样的实体中添加字段时
public class Entity {
private int id;
private List<String> codes;
private List<Integer> anotherCodes;
private String description;
//constructor + getters/setters
}
@Repository
class EntityRepository {
private final ResultSetExtractor<List<Entity>> resultSetExtractor =
JdbcTemplateMapperFactory
.newInstance()
.addKeys("id")
.unorderedJoin()
.newResultSetExtractor(Entity.class);
@Autowired
private NamedParameterJdbcOperations jdbcOperations;
List<Entity> getAll() {
return jdbcOperations.query(
"SELECT id,
code as codes,
anothercode as anotherCodes,
description FROM table", resultSetExtractor);
}
}
然后我做同样的事情并得到结果:
Entity[id=1,
codes={"111", "111", "111", "222", "222", "222", "333", "333", "333"},
anotherCodes={"1111", "2222", "2222", "1111", "2222", "2222", "1111", "2222", "2222"}
description="description1"]
但是我想得到这个:
Entity[id=1,
codes={"111", "222", "333"},
anotherCodes={"1111", "2222"}
description="description1"]
我该如何解决??? 请不要建议更改表或将其分开。我已经有生产项目,所以我不能这样做
答案 0 :(得分:0)
您应该使用GROUP BY ID,并使用GROUP_CONCAT:
List<Entity> getAll() {
return jdbcOperations.query(
"SELECT id,
GROUP_CONCAT(code) as codes,
GROUP_CONCAT(anothercode) as anotherCodes,
description FROM table
GROUP BY id", resultSetExtractor);
}
请注意,取决于您的版本,DB可能会抱怨描述的选择,因为它不在GROUP BY子句中。 在这种情况下,您应该