如何把java对象持久化,存到数据库?总的思路是:
(1)先把除BLOB流以外的字段先存入数据库
(2)再把那条记录取出来,把BLOB字段赋予一个blob变量
(3)用一个BufferedOutputStream把messageStream对象中的流注入stream
Connection con= ConnectionFactory.getConnection();
Statement stmt;
String sql;
try {
/* 设定不自动提交 */
boolean defaultCommit = con.getAutoCommit();
con.setAutoCommit(false);
// 数据库连接
stmt = con.createStatement();
// 先从数据库中取出一个序列号ID
String id = "";
ResultSet rs = stmt.executeQuery("select SEQ_"
+ tableName.substring(3, tableName.length())
+ ".NEXTVAL from dual ");
if (rs.next()) {
id = rs.getString(1);
}
// 先把除BLOB流以外的字段先存入数据库
sql = "insert into " + tableName + " values ("+ id + ","
+ messageStream.getServiceCode() + ",EMPTY_BLOB())";
stmt.executeUpdate(sql);
// 再把那条记录取出来,把BLOB字段赋予一个blob变量
sql = "select MESSAGESTREAM from " + tableName + " where id=" + id;
rs = stmt.executeQuery(sql);
while (rs.next()) {
BLOB stream = (BLOB) rs.getBlob(1);
// 用一个BufferedOutputStream把messageStream对象中的流注入stream
BufferedOutputStream bout = new BufferedOutputStream(stream
.getBinaryOutputStream(1));
bout.write(messageStream.getMessageStream());
// 提交
bout.flush();
bout.close();
}
con.commit();
stmt.close();
/* 恢复原提交状态 */
con.setAutoCommit(defaultCommit);
} catch (SQLException ex) {
con.rollback();
log.error(Thread.currentThread().getName()+" 数据库出错。",ex);
} catch (IOException e) {
// TODO Auto-generated catch block
log.error(Thread.currentThread().getName()+" 输出流出错",e);
}