0

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);
ghovat
  • 1,033
  • 1
  • 12
  • 38

2 Answers2

1

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);
Hitobat
  • 2,847
  • 1
  • 16
  • 12
  • Thanks. Thats what I am currently doing but I was wondering if there is not a more elegant way – ghovat Oct 13 '18 at 12:44
  • 1
    The alternative is that you mapper class first checks to see if the column is available, before trying to extract the value. e.g. Using findColumn or similar then catching the exception. – Hitobat Oct 13 '18 at 12:48
1

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