Java实现对象序列化保存到数据库
时间:2010-6-13
Java对象序列化就那些实现了Serializable接口的对象转换成一个字节序列,并能够在以后将这个字节序列 完全恢复为原来的对象。这一过程甚至可以通过网络进行;运行Windows操作系统的计算机上创建的一个对象将其序列化,通过网络将它发送到一台运行Unix系统的计算机,然后在那里准确地重新组装。Java序列化的一个引用就是RMI,当向远程对象发送消息,需要通过对象序列化来传输参数和返回值。
PS:通过序列化之后我们可以将对象保存到持久化的设备如文件、数据库
实现:
实现Serializable接口。这个接口是标记接口里面没有什么方法要实现的!然后使用一个输出流(如:FileOutputStream) 构造一个ObjectOutputStream(对象流)。然后用ObjectOutputStream的writeObject(Object obj)方法就可以将参数为obj的对象写出保存其状态。如果要恢复的话就使用输入流实现!
1.数据表结构
CREATE TABLE `obj` (
`id` int(11) NOT NULL auto_increment,
`object` blob,
PRIMARY KEY(`id`)
) ENGINE=InnoDB
AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
2.读写代码
packageorg.test;
importjava.io.*;
importjava.util.ArrayList;
importjava.util.Date;
importjava.util.List;
importjava.sql.Blob;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.Statement;
publicclassObjectSerial {
publicstaticvoidmain(String[] args) {
//创建测试用对象
City beijing =newCity();
beijing.setName("北京");
beijing.setCode("010");
City shanghai =newCity();
shanghai.setName("上海");
shanghai.setCode("020");
City tianjin =newCity();
tianjin.setName("天津");
tianjin.setCode("021");
ListcityList =newArrayList();
cityList.add(beijing);
cityList.add(shanghai);
cityList.add(tianjin);
TestObject obj =newTestObject();
obj.setName("yangsq");
obj.setPassword("111");
obj.setDate(newDate());
obj.setCityList(cityList);
try{
//将对象存入blob字段
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","321");
con.setAutoCommit(false);
//将一个对象序列化保存到数据库
PreparedStatement pstmt = con.prepareStatement("insert into obj (object) values (?)");
pstmt.setObject(1, obj);
pstmt.executeUpdate();
con.commit();
//从数据库中提取记录
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("select object from obj");
if(rs.next()) {
//以下是读取的方法一定要注意了!
Blob inblob = (Blob) rs.getBlob("object");
InputStream is = inblob.getBinaryStream();
BufferedInputStream input =newBufferedInputStream(is);
byte[] buff =newbyte[(int) inblob.length()];//放到一个buff字节数组
while(-1 != (input.read(buff, 0, buff.length)));
ObjectInputStream in =newObjectInputStream(newByteArrayInputStream(buff));
TestObject w3 = (TestObject)in.readObject();//从IO流中读取出来.可以得到一个对象了
System.out.println(w3.getName());
System.out.println(w3.getPassword());
System.out.println(w3.getDate());
}
}catch(Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
}
classTestObjectimplementsSerializable {
privatestaticfinallongserialVersionUID= 4558876142427402513L;
/**
*@paramargs
*/
privateStringname;
privateStringpassword;
privateDatedate;
privateListcityList;
publicListgetCityList() {
returncityList;
}
publicvoidsetCityList(ListcityList) {
this.cityList= cityList;
}
publicDate getDate() {
returndate;
}
publicvoidsetDate(Date date) {
this.date= date;
}
publicString getName() {
returnname;
}
publicvoidsetName(String name) {
this.name= name;
}
publicString getPassword() {
returnpassword;
}
publicvoidsetPassword(String password) {
this.password= password;
}
}
classCityimplementsSerializable{
privatestaticfinallongserialVersionUID= 4558876127402513L;
privateStringname;
privateStringcode;
publicString getCode() {
returncode;
}
publicvoidsetCode(String code) {
this.code= code;
}
publicString getName() {
returnname;
}
publicvoidsetName(String name) {
this.name= name;
}
}