使用JDBI将2d数组插入PostreSQL DB?

时间:2015-10-11 07:18:45

标签: java postgresql jdbi

我可以使用SQL Object API将public class Game { protected int id; protected int whoseTurn; protected int winner; protected char[][] board; public Game(int id, int turn, int winner, char[][] board ) { this.id=id; this.whoseTurn=turn; this.winner=winner; this.board=board; } @JsonProperty public int getId() { return id; } @JsonInclude(Include.NON_NULL) public int getWhoseTurn() { return whoseTurn; } @JsonInclude(Include.NON_NULL) public int getWinner() { return winner; } public char[][] getBoard() { return board; } } 映射到@RegisterMapper(GameMapper.class) public interface GameDAO { @SqlUpdate("create table if not exists GAMES (ID integer, WHOSE_TURN varchar(10), WINNER varchar(10), BOARD char(1)[][])") void createTableIfNotExists(); @SqlUpdate("insert into GAMES (ID, WHOSE_TURN, WINNER, BOARD) values (:id, :whoseTurn, :winner, :board)") void insert(@BindBean Game game); } 数据库中的一行吗?这是我的尝试:

数据类:

insert

DAO:

org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of [[C. Use setObject() with an explicit Types value to specify the type to use.

调用[[C时出现此错误:

{{1}}

什么是{{1}}?我能以某种方式完成这项工作吗?如果不是,我真的很感激另类。

1 个答案:

答案 0 :(得分:2)

JDBI不知道如何投射数组类型。所以我们需要为char [] []定义ArgumentFactory。

import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.Argument;
import org.skife.jdbi.v2.tweak.ArgumentFactory;

import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class CharArrayArgument implements ArgumentFactory<char[][]> {
    @Override
    public boolean accepts(Class<?> expectedType, Object value, StatementContext ctx) {
        return value != null && char[][].class.isAssignableFrom(value.getClass());
    }

    @Override
    public Argument build(Class<?> expectedType, final char[][] value, StatementContext ctx) {
        return new Argument() {
            @Override
            public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
                Array values = statement.getConnection().createArrayOf("char", value);
                statement.setArray(position, values);
            }
        };
    }
}

将此argumentFactory注册到dbi。它应该工作。

    dbi.registerArgumentFactory(new CharArrayArgument());
    GameDao gameDao = dbi.open(GameDao.class);
    Game game = new Game(1, 2, 3, new char[][]{{'a'}, {'b'}});

    gameDao.createTableIfNotExists();
    gameDao.insert(game);