ghovat
ghovat

Reputation: 1043

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);

Upvotes: 0

Views: 2024

Answers (2)

Piyush Upadhyay
Piyush Upadhyay

Reputation: 105

You can retrieve the values whatever you want and before passing the values to Tag constructor check their existence in the ResultSet. If the attribute is not present then you can pass the default value for the attributes. You can check the value as r.getString("tag_uuid") != null (for strings) then tag_uuid = r.getString("tag_uuid")

Upvotes: 1

Hitobat
Hitobat

Reputation: 3037

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);

Upvotes: 1

Related Questions