arnaudroger / SimpleFlatMapper

Fast and Easy mapping from database and csv to POJO. A java micro ORM, lightweight alternative to iBatis and Hibernate. Fast Csv Parser and Csv Mapper
http://simpleflatmapper.org
MIT License
438 stars 76 forks source link

Duplicate object with same id, despite ordered by id and added @Key annotation. #757

Open GlenGGG opened 3 years ago

GlenGGG commented 3 years ago

I am using Sql2o 1.6.0 with sql2o-postgres:1.6.0 with sfm-sql2o-jre9:8.2.3.

I have two POJOs, they are:

public class Post {
  @Key
  private String id;  // This is generated from application side using UUID.randomUUID.toString
  private List<Image> images;
}

public class Image {
  @Key
  private String id;
  private String postId;
  private String url;
}

When I try to read post from a PostgreSQL database using sql2o and sfm, I get duplicate posts with the same id using the following code:

    try(Connection conn = sql2o.open())
    {
      Query query = conn.createQuery(
          "SELECT post.*," +
          "image.id as images_id," +
          "image.post_id as images_post_id," +
          "image.url as images_url " +
          "FROM post " +
          "LEFT JOIN image on image.post_id=post.id " +
          "ORDER BY post.id;");
      query.setAutoDeriveColumnNames(true);
      query.setResultSetHandlerFactoryBuilder(new SfmResultSetHandlerFactoryBuilder(JdbcMapperFactory.newInstance().addKeys("id", "images_id")));
      List<Post> posts = query.executeAndFetch(Post.class);
}

From the resulting posts I can see SimpleFlatMapper seems to recognize each row of the resulting set as a separate object. Each post in the resulting list has only one image in images, which corresponds exactly to each row in the resulting joint table. I have ordered the post id and added @Key to keys and added keys to the factory, I don't know what went wrong. Is it something to do with my ids, because they are strings.

Sorry if this is a duplicate issue.