Saving java object to PostgreSQL problem

2019-07-10 07:35发布

问题:

I'm trying to save an object in a postgre column(bytea) with the following code:

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

But i'm getting this exeption :

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

i guess, that there is no setBinaryStream(int , InputStream) implemented in the jdbc4. There is any other way to do so ?

回答1:

You need to use setBinaryStream(int, InputStream, int) where the third parameter denotes the length of the input stream in bytes.

So in your case this would be something like:

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