0

当我使 DAO 可序列化时,我有 DAO 我得到异常:

 Cannot serialize session attribute com.sun.faces.renderkit.ServerSideStateHelper.LogicalViewMap for session C354B1B6053088CBB8E8A933E5F8EAE0
    java.io.NotSerializableException: org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper

我的道:

public boolean getConnection() {
        try {
            InitialContext context = new InitialContext();
            DataSource dataSource = (DataSource) context.lookup("java:/comp/env/jdbc/Orcl");
            connection = dataSource.getConnection();
            return true;
        } catch (SQLException ex) {
            Logger.getLogger(KPIDAO.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (NamingException ex) {
            Logger.getLogger(KPIDAO.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

在控制器 (@ViewScoped) 中:

KPIDAO kpiDAO = new KPIDAO();

上下文.xml

<Resource 
        name="jdbc/Orcl" 
        auth="Container"
        type="javax.sql.DataSource" 
        username="username" 
        password="password"
        driverClassName="oracle.jdbc.OracleDriver" 
        url="jdbc:oracle:thin:@192.168.1.10:1521:XE"
        maxActive="8" 
   />

什么是正确的解决方案?

4

2 回答 2

1

例如

@ViewScoped
public class ViewBean implements Serializable{
  private transient KPIDAO kpiDAO = //get singleton instance from factory
  //also dont keep connection object as instance variable, fetch it from pool in methods and perform db operations.

  private void readObject(java.io.ObjectInputStream stream)
        throws java.io.IOException, ClassNotFoundException
    {
        stream.defaultReadObject();

        // assign reference manually.
        this.kpiDAO  =  //get from factory;
    }

private void writeObject(java.io.ObjectOutputStream stream)
        throws java.io.IOException
    {

        stream.defaultWriteObject();
    }
}

注意:如果您将连接对象从实例变量移动到本地方法变量,您也不需要上面的代码。

更新:

从您的代码片段和异常

connection = dataSource.getConnection();

它似乎是一个实例变量。

IE

public class Dao {
 private Connection connection; //instance variable
}

将其更改为

public class Dao {

 public List<Bean> getResult(){
  //local method variable
  Connection connection = //get from pool
  //perform db operation with connection object
 }

}

于 2012-07-20T08:04:48.707 回答
0

您不应该在会话中存储对 PoolingDataSource 的引用,因为 PoolingDataSource 不可序列化。我建议您将它存储在其他地方,例如在应用程序上下文中。

于 2012-07-19T09:44:37.397 回答