Y.S. Yuan
Y.S. Yuan

Reputation: 101

How to select results of text array type in mybatis?

For example, there is a table, which has a column of type text[], in PostgreSQL:

CREATE TABLE t
(
    id integer,
    name text,
    tags text[],
    PRIMARY KEY (id)
)

Now, I want to select tags in two ways:

  1. Select tags using primary key id, and the result should be of type List<String>
  2. Select tags using name, and the result should be of type List<List<String>>

How should I write MyBatis mapper to achieve this?

Upvotes: 1

Views: 13308

Answers (2)

Ancoron
Ancoron

Reputation: 2733

You're not the first one with this issue.

The project common-mybatis has a type handler exactly for this use case: StringArrayTypeHandler

Just add it to the MyBatis configuration:

    <typeHandlers>
        <typeHandler handler="org.gbif.mybatis.type.StringArrayTypeHandler"/>
    </typeHandlers>

...and then for the mapping it is as simple as:

    <select id="getTagsById" resultType="java.util.List">
        SELECT tags FROM t WHERE id = #{id}
    </select>

    <select id="getTagsByName" resultType="java.util.List">
        SELECT tags FROM t WHERE name = #{name}
    </select>

...and in the code:

try (SqlSession session = sessionFactory.openSession()) {
    List<String> tags = session.selectOne("[...].getTagsById", 1);
    System.out.println("Tags: " + tags);

    List<List<String>> multiTags = session.selectList("[...].getTagsByName", "test");
    System.out.println("Tags: " + multiTags);
}

Tested against a PostgreSQL 11 with JDBC driver version 42.2.5 and the following test data:

select * from t;
 id |  name   |                tags                
----+---------+------------------------------------
  1 | test    | {Thriller,Drama}
  2 | my name | {Science-Fiction,Adventure,Horror}
  3 | test    | {Comedy,Adventure}
(3 rows)

...produces:

Tags: [Thriller, Drama]
Tags: [[Thriller, Drama], [Comedy, Adventure]]

Upvotes: 1

ave
ave

Reputation: 3594

You can still use Java mapper, however, MyBatis internally calls SqlSession#selectList when the return type is List and that is not what you want.
So, you need to use Object as the return type instead.

@Select("select tags from t where id = #{id}")
Object getTagById(Integer id);

@Select("select tags from t where name = #{name}")
List<Object> getTagByName(String name);

And register your type handler globally in the config. i.e.

<typeHandlers>
  <typeHandler handler="xxx.yyy.ListArrayTypeHandler" />
</typeHandlers>

or

configuration.getTypeHandlerRegistry()
  .register(ListArrayTypeHandler.class);

For completeness, here is an example type handler implementation.

import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

@MappedJdbcTypes({ JdbcType.ARRAY })
@MappedTypes({ Object.class })
public class ListArrayTypeHandler extends BaseTypeHandler<List<?>> {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i,
      List<?> parameter, JdbcType jdbcType) throws SQLException {
    //  JDBC type is required
    Array array = ps.getConnection().createArrayOf("TEXT", parameter.toArray());
    try {
      ps.setArray(i, array);
    } finally {
      array.free();
    }
  }

  @Override
  public List<?> getNullableResult(ResultSet rs, String columnName) throws SQLException {
    return extractArray(rs.getArray(columnName));
  }

  @Override
  public List<?> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return extractArray(rs.getArray(columnIndex));
  }

  @Override
  public List<?> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return extractArray(cs.getArray(columnIndex));
  }

  protected List<?> extractArray(Array array) throws SQLException {
    if (array == null) {
      return null;
    }
    Object javaArray = array.getArray();
    array.free();
    return new ArrayList<>(Arrays.asList((Object[])javaArray));
  }
}

FYI, to store a List into the tags column, you may have to specify the type handler explicitly.

insert into t (...) values (#{id}, #{name},
  #{tags,typeHandler=xxx.yyy.ListArrayTypeHandler})

Upvotes: 1

Related Questions