将java对象保存为PostgreSQL问题

时间:2010-11-28 23:30:59

标签: java sql postgresql serialization jdbc

我正在尝试使用以下代码在postgre列(bytea)中保存对象:

Utilisateur utilisateur = new Utilisateur("aa","aa","aa",10,"aaammm",12,Role.ADMINISTRATEUR);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(utilisateur);
        oos.close();
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

        Connection connection = null;
        PreparedStatement preparedStatement = null;


        connection = Connect();
        String SOME_SQL= "INSERT INTO test (id, objet) VALUES( ?, ?)";
        preparedStatement = connection.prepareStatement(SOME_SQL);
        preparedStatement.setBinaryStream(2, bais);
        preparedStatement.setInt(1, 11);
        preparedStatement.executeUpdate();
        preparedStatement.close();

但是我得到了这个例子:

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
    at org.eclipse.ve.internal.java.vce.launcher.remotevm.JavaBeansLauncher.main(JavaBeansLauncher.java:86)
Caused by: org.postgresql.util.PSQLException: Function org.postgresql.jdbc4.Jdbc4PreparedStatement.setBinaryStream(int, InputStream) is not implemented.
    at org.postgresql.Driver.notImplemented(Driver.java:753)
    at org.postgresql.jdbc4.AbstractJdbc4Statement.setBinaryStream(AbstractJdbc4Statement.java:129)
    at com.grst.connector.SerializeToDatabase.<init>(SerializeToDatabase.java:35)
    ... 5 more

我猜,在jdbc4中没有实现setBinaryStream(int,InputStream)。还有其他方法吗?

1 个答案:

答案 0 :(得分:9)

您需要使用setBinaryStream(int, InputStream, int),其中第三个参数表示输入流的长度(以字节为单位)。

所以在你的情况下,这将是:

byte[] data = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(data);
..
..
preparedStatement.setBinaryStream(2, bais, data.length);