4

我正在使用 SPRING 框架,我目前正在尝试在创建新条目(行)时将数组添加到我的数据库中。有问题的列称为“关键字”。所以这是我的 sql 初始化代码(对我来说看起来不错)

CREATE TABLE IF NOT EXISTS Email (
    Email_Id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    Sender_Email VARCHAR(255) NOT NULL,
    Recipient_Email VARCHAR(255) NOT NULL,
    Subject VARCHAR(255) NOT NULL,
    Body TEXT,
    Attachment_Path VARCHAR(255) NOT NULL,
    Creation_Date DATETIME NOT NULL,
    MaxKeywords INT UNSIGNED NOT NULL,
    Keywords VARCHAR(255) NOT NULL,
    Primary Key(Email_Id)
);

这是我的 add 函数中崩溃和烧毁的代码:

public boolean add(final MessageDto emailDto){
    boolean result = false;
    int rowsAffected;
    KeyHolder keyHolder = new GeneratedKeyHolder();
    final String sql;

    sql = "INSERT INTO email (Sender_Email, Recipient_Email, Subject, Body, Attachment_Path, Creation_Date, MaxKeywords, Keywords) " +
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

    try{
        rowsAffected = getJdbcTemplate().update(
                  new PreparedStatementCreator() {
                        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                            PreparedStatement statement = 
                                    connection.prepareStatement(sql, new String[] {"emailId"});

                            String[] foo = {"A","B"};

                            statement.setString(1, emailDto.getFrom());
                            statement.setString(2, emailDto.getTo());
                            statement.setString(3, emailDto.getSubject());
                            statement.setString(4, emailDto.getBody());
                            statement.setString(5, emailDto.getAttachmentPath());
                            statement.setTimestamp(6, new Timestamp(emailDto.getCreationDate().getMillis()));
                            statement.setInt(7, emailDto.getMaxKeywordCount());
                            statement.setArray(8, connection.createArrayOf("varchar", foo));

                            return statement;
                        }
                      }, keyHolder);

        if(rowsAffected > 0){
            emailDto.setEmailId(keyHolder.getKey().intValue());
            result = true;
        }
    } catch (Exception e){
        throw new RuntimeException(e);
    }

    return result;
}

抛出的错误是:

org.springframework.dao.InvalidDataAccessApiUsageException: PreparedStatementCallback; SQL []; null; nested exception is java.sql.SQLFeatureNotSupportedException

帮助?

4

1 回答 1

0

如果您决定放弃该setArray方法,您可以这样做。使用您自己的逻辑将数组转换为字符串。无论如何,您将其存储在 a 中varchar,因此您必须“展平”数组。

    String[] foo = {"A","B"};
    StringBuilder sb = new StringBuilder();
    for (String bar : foo) {
        sb.append(bar);
        sb.append("\t");
    }
    statement.setArray(8, sb.toString());
于 2013-03-30T03:35:41.150 回答