Recentemente migrato a POSTGRESQL, sto cercando di ottenere la chiave generata in modo univoco sulla creazione di una nuova voce nella tabella db. La tabella screenstable
assomiglia a questo:Spring: Come utilizzare KeyHolder con PostgreSQL
CREATE TABLE screenstable
(
id serial NOT NULL,
screenshot bytea,
CONSTRAINT screen_id PRIMARY KEY (id)
)
Il metodo che inserisce i dati in screenstable
è la seguente:
@Autowired NamedParameterJDBCTemplate template;
public int insertImage(ImageBean imageBean){
String query = "insert into screenstable (screenshot) values (:image)";
SqlParameterSource data = new BeanPropertySqlParameterSource(imageBean);
KeyHolder keyHolder = new GeneratedKeyHolder();
template.update(query, data, keyHolder);
return keyHolder.getKey().intValue();
}
e ImageBean
è
import java.util.Arrays;
public class ImageBean {
private int id;
private byte[] image;
@Override
public String toString() {
return "ImageBean [id=" + id + ", image=" + Arrays.toString(image)
+ "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
Ma l'esecuzione del codice danno la seguente eccezione
15:33:20,953 ERROR JsonParseExceptionMapper:15 - org.springframework.dao.InvalidDataAccessApiUsageException: The getKey method should only be used when a single key is returned. The current key entry contains multiple keys: [{id=3, screenshot=[[email protected]}]
org.springframework.dao.InvalidDataAccessApiUsageException: The getKey method should only be used when a single key is returned. The current key entry contains multiple keys: [{id=3, screenshot=[[email protected]}]
at org.springframework.jdbc.support.GeneratedKeyHolder.getKey(GeneratedKeyHolder.java:65)
at some.project.model.FeedbackDao.insertImage(FeedbackDao.java:20)
at some.project.rest.FeedsRest.pluginCheck(FeedsRest.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597).....
Lo stesso codice utilizzato per funzionare correttamente in caso di MySQL
ma non funziona con le chiavi quando viene utilizzato con POSTGRES. Il tipo di dati serial
è in qualche modo responsabile della mancata esecuzione del codice o è possibile che io stia utilizzando correttamente la funzione chiave primaria?
Si prega di consulenza.
il metodo 'getKey()' restituisce un 'Numero', quindi non riesco ad accedervi come una mappa. si prega di controllare http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/jdbc/support/KeyHolder.html –