简体   繁体   中英

java.io.NotSerializableException: org.postgresql.jdbc4.Jdbc4Connection

I have a managed bean with view scope. The problem is that when I run the web application I have the following error:

GRAVE: Error Rendering View[/login.xhtml]
java.io.NotSerializableException: org.postgresql.jdbc4.Jdbc4Connection
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
    at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
    at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
    at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
    at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
    at java.io.ObjectOutputStream.writeObject0(Unknown Source).........

But when I change the scope to session or request, everything works just fine. Can anyone tell my if I have done anything wrong? Maybe I forgot a configuration or something?

You've assigned a JDBC Connection as a property of the view scoped managed bean. View scoped managed beans and all of its properties needs to be serializable as they will be stored in the session. The Connection interface does however not extend Serializable and hence this exception. You would need to make it transient .

But the real problem is actually bigger; holding external resources as a field of a class is an extremely bad idea. You should never hold DB resources as a field of a class which lives longer than the resource needs to be kept open. Otherwise they will leak away and/or will cause threadsafety and transactional problems (deadlocks and so on) and/or will be reclaimed by the DB and will thus stop working.

You should always open and close the connection (and statement and resultset) in the shortest possible scope, preferably inside a try-finally block of the very same method block. If you want to improve connecting performance, then you should be using a connection pool.

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM