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
435 stars 76 forks source link

Mapping One-To-Many and adding nullable column to Map throws java.lang.IllegalArgumentException ("Already has key") #759

Open WorkAccountM opened 3 years ago

WorkAccountM commented 3 years ago

Hi, first things first: Thank you for creating such a wonderful piece of software :)

I am having trouble when mapping columns that are nullable to a Map. Let's take this Query as an example:

SELECT a.author_id as id, a.name as map_name, b.name as books_name
                    FROM authors a
                    LEFT OUTER JOIN books b
                    ON a.author_id = b.author_id
                    ORDER by id;

Now let's assume the objects look like this:

public class Author {
    String id;
    Map<String, String> map;
    List<Book> books;
}

public class Book {
    String name;
}

I would then do something like this:

  ResultSetExtractor<List<Author>> resultSetExtractor =
                JdbcTemplateMapperFactory
                        .newInstance()
                        .addKeys("id")
                        .newResultSetExtractor(Author.class);

        List<Author> results = template.query(AUTHOR_QUERY, resultSetExtractor);

This will fail if the actual tables look like this:

INSERT INTO authors(author_id, name) VALUES ('Author1', null);

INSERT INTO books(book_id, author_id, name) VALUES ('Book1' 'Author1', 'Harry Potter');
INSERT INTO books(book_id, author_id, name) VALUES ('Book2' 'Author1', 'Harry Potter returns');

It would not fail, if instead of a map, I would be using an actual property. This is not possible for my use case however. It would also work, if the property could not be null, then SimpleFlatMapper seems to correctly flatten the object. I tried to exclude null values from the map but the documentation only mentions "addKeys" for this and adding the author name as a key simply turned the whole map into null, even if there are other properties like a author email for example, that could be mapped and is not nullable. Changing the MapPropertyType also did not work. If there would be a way to simply stop SimpleFlatMapper from adding null Values to the map, the problem would be solved as well but that should probably be configurable and the map should still work for other properties that are not null and can be added to the map.

Best Regards