java 序列化数据到mysql/ target=_blank class=infotextkey>mysql数据库中的方法,有需要的朋友可以参考下。
注:使用hibernate跟数据库打交道。
hibernate配置文件如下
hibernate映射文件
hibernate实体类
待序列化的类
测试类
package test.java;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class MySerialization {
public static SessionFactory sessionFactory=null;
public static SessionFactory getSessionFactory(){
if(sessionFactory==null)
sessionFactory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
return sessionFactory;
}
public static Blob getBlob(Object object) throws IOException{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
ByteArrayInputStream bis=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
return Hibernate.createBlob(bis);
}
public static void writeObjectToDB(Object object) throws IOException{
Test test=new Test();
test.setContent(getBlob(object));
Session session=getSessionFactory().openSession();
Transaction tx =session.beginTransaction();
session.save(test);
tx.commit();
session.close();
}
public static User readObjectFromDB(int id) throws IOException, SQLException, ClassNotFoundException{
Session session=getSessionFactory().openSession();
Test test=(Test) session.get(Test.class,id);
ObjectInputStream objectInputStream=new ObjectInputStream(test.getContent().getBinaryStream());
return (User)objectInputStream.readObject();
}
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
User user=new User();
user.setId(1);
user.setAge(22);
user.setName("zhangsan");
writeObjectToDB(user);
User user1=readObjectFromDB(2);
System.out.println(user1.getId());
System.out.println(user1.getName());
System.out.println(user1.getAge());
}
}