gpt4 book ai didi

java - DBCP 中的不可序列化异常

转载 作者:行者123 更新时间:2023-12-01 15:16:16 25 4
gpt4 key购买 nike

当我使 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

我的 DAO:

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;
}
}

在 Controller (@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"
/>

什么是正确的解决方案?

最佳答案

例如

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

Note: In case you move connection object from instance variable to local method variables, you won't need above code too.

更新:

来自您的代码片段和异常

connection = dataSource.getConnection();

它似乎是一个实例变量。

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
}

}

关于java - DBCP 中的不可序列化异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11557571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com