Search code examples
javapostgresqldropwizardpojojdbi

Dropwizard JDBI 3 ResultSetMapper ignore field


I have this Pojo:

private long id;

    @NotEmpty
    @JsonProperty("name")
    private String name;

    @NotEmpty
    @JsonProperty("id")
    private String tagUuid;

    @NotEmpty
    @JsonProperty("archived")
    private boolean archived;

    @NotEmpty
    @JsonProperty("creationDate")
    private DateTime creationDate;

    private Integer count;

    @JsonCreator
    public Tag() {
    }

    public Tag(long id, String tagUuid, String name, boolean archived, Timestamp creationDate, Integer count) {
        this.id = id;
        this.tagUuid = tagUuid;
        this.name = name;
        this.archived = archived;
        this.creationDate = new DateTime(creationDate);
        this.count = count;
    }

This is my result set mapper:

public class TagMapper implements ResultSetMapper<Tag> {

    @Override
    public Tag map(int index, ResultSet r, StatementContext ctx) throws SQLException {
        return new Tag(
                r.getLong("id"),
                r.getString("tag_uuid"),
                r.getString("name"),
                r.getBoolean("archived"),
                r.getTimestamp("creation_date"),
                r.getInt("count")
        );
    }
}

How can I fetch from the database one column less. For example in some queries I fetch only tagUuid and name and not the other fields. But if I do this I get this exception: org.skife.jdbi.v2.exceptions.ResultSetException: Exception thrown while attempting to traverse the result set. I tried to create a addtional Tag Constructor without the other parameters.

This is the query I try to run:

@SqlQuery("SELECT t.id, t.tag_uuid as tag_uuid, t.name, t.archived, t.creation_date FROM tags t WHERE t.tag_uuid = :tag_uuid LIMIT 1")
    public Tag fetchTagByUuid(@Bind("tag_uuid") String tagUuid);

Solution

  • You can just return the extra column in your query SQL.

    @SqlQuery("SELECT t.id, t.tag_uuid as tag_uuid, t.name, t.archived, " +
              "t.creation_date, 0 AS count FROM tags t " +
              "WHERE t.tag_uuid = :tag_uuid LIMIT 1")
    public Tag fetchTagByUuid(@Bind("tag_uuid") String tagUuid);