2015-09-28 121 views
2

我正面臨着spring-jdbc的枚舉問題。我有一個包含枚舉值的POJO。我想將字符串值存儲在數據庫中,而不是序號。我做了一個DAO,除了具有namedParameterJdbcTemplate的批處理方法(對於jdbcTemplate和BatchPreparedStatementSetter它可以工作,但我更喜歡使用命名參數),它工作得很好。無法使用spring-jdbc以批處理方式存儲Enum NamedParameterJdbcTemplate

例如:

public int[] batchUpdate(List<MyPojo> pojos) throws DaoException { 
    SqlParameterSource[] parameters = new SqlParameterSource[pojos.size()]; 

    for (int i = 0; i < pojos.size(); i++) { 
     parameters[i] = new BeanPropertySqlParameterSource(pojos.get(i)); 
    } 

    try { 
     return namedParameterJdbcTemplate.batchUpdate(SQL_UPDATE, (SqlParameterSource[]) parameters); 
    } catch (Exception ex) { 
     throw new DaoException(ex); 
    } 
} 

不適用於枚舉屬性的作用。

我有這樣的錯誤:

Caused by: org.h2.jdbc.JdbcSQLException: Value too long for column "STATUS CHARACTER VARYING(20) NOT NULL": "'aced00057e7200466f72672e67656e792e7064702e6669726562697264732e67656e79746f74652e646f6d61696e6d6f64656c2e6265742e4265744465636f6... (258)"; SQL statement: UPDATE ... SET ..., status = ? WHERE id = ? [22001-187] at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) at org.h2.message.DbException.get(DbException.java:179) at org.h2.table.Column.validateConvertUpdateSequence(Column.java:327) at org.h2.table.Table.validateConvertUpdateSequence(Table.java:737) at org.h2.command.dml.Update.update(Update.java:125) at org.h2.command.CommandContainer.update(CommandContainer.java:78) at org.h2.command.Command.executeUpdate(Command.java:254) at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:157) at org.h2.jdbc.JdbcPreparedStatement.executeBatch(JdbcPreparedStatement.java:1183) at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:1005) at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:989) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:644) ... 43 more

MyPojo有枚舉值(狀態)。這很奇怪,因爲我想存儲的枚舉字符串'驗證'而不是'aced000 ...'。如果我使用的是JPA,我會在狀態字段中使用@Enumerated(EnumType.STRING),但是在spring-jdbc中存在這樣的東西嗎?

問候

回答

1

通過註冊SQL類型終於解決:

for (int i = 0; i < bets.size(); i++) { 
     BeanPropertySqlParameterSource bpsps = new BeanPropertySqlParameterSource(pojos.get(i)); 
     bpsps.registerSqlType("status", Types.VARCHAR); 
     parameters[i] = bpsps; 
    }