当我制作DAO Serializable时我有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;
}
}
在控制器(@ViewScoped)中:
KPIDAO kpiDAO = new KPIDAO();
context.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"
/>
什么是正确的解决方案?
答案 0 :(得分: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();
它似乎是一个实例变量。
即
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
}
}
答案 1 :(得分:0)
您不应该在会话中存储对PoolingDataSource的引用,因为PoolingDataSource不可序列化。我建议你把它存放在其他地方,例如在应用程序上下文中。