gpt4 book ai didi

java - 使用 JDBI 将二维数组插入 PostreSQL DB?

转载 作者:行者123 更新时间:2023-11-29 13:00:02 25 4
gpt4 key购买 nike

我可以使用 SQL 对象 API 将 Game 映射到 GAMES 数据库中的一行吗?这是我的尝试:

数据类:

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 被调用时,我得到这个错误:

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?我能以某种方式完成这项工作吗?如果没有,我真的很感激一个替代方案。

最佳答案

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

关于java - 使用 JDBI 将二维数组插入 PostreSQL DB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33062516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com