在Spring(数据库)中将相似的行合并为一个实体

时间:2019-12-16 13:19:39

标签: java spring spring-data rowmapper

我有问题。我的数据库表名为“表”,看起来像这样(现在由3行组成,它们实际上是相同的实体,但是使用不同的代码)

enter image description here

我也有一个实体

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"]

但是

当我向这样的实体中添加字段时

enter image description here

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"]

我该如何解决??? 请不要建议更改表或将其分开。我已经有生产项目,所以我不能这样做

1 个答案:

答案 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子句中。 在这种情况下,您应该

  1. 将其放在GROUP BY中,但是如果您对同一个ID有多个描述,则会得到两行。
  2. 做出任意选择,例如FIRST_VALUE(description)