【6.1】大对象映射

1.在pojo类中 用Blob类和Clob

说明:CLOB和BLOB的区别【具体参考博文:http://blog.csdn.net/magister_feng/article/details/7825892

  CLOB使用CHAR来保存数据。 如:保存XML文档。

      BLOB就是使用二进制保存数据。 如:保存位图。

public class Student {
	private int id;
	private String name;
	private int age;
	//存放大数据  可以存放4G的内容
	private Blob image;
	private Clob introduce;
//省略get/set
	}

  

2.在hbm文件中 需指定对应类型

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.siggy.pojo">
	<class name="Student">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="name"/>
		<property name="age"/>
		<property name="image" type="java.sql.Blob"/>
		<property name="introduce" type="java.sql.Clob"/>
	</class>
</hibernate-mapping>

  

3.测试

package cn.siggy.test;

import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;

import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialClob;
import javax.sql.rowset.serial.SerialException;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

import cn.siggy.pojo.Student;
import cn.siggy.util.HibernateUtil;

public class HibernateTest {
	@Test
	public void testCreateDB(){
		Configuration cfg = new Configuration().configure();
		SchemaExport se = new SchemaExport(cfg);
		//第一个参数 是否生成ddl脚本  第二个参数  是否执行到数据库中
		se.create(true, true);
	}
	@Test
	public void testSave() throws HibernateException, SerialException, SQLException{
		Session session = null;
		Transaction tx = null;
		try{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			Student stu = new Student();
			stu.setName("尹志平");
			stu.setAge(23);
			
			Blob blob = new SerialBlob("ttt".getBytes());
			Clob clob = new SerialClob("sss".toCharArray());
			stu.setImage(blob);
			stu.setIntroduce(clob);
			session.save(stu);
			
			tx.commit();
			
		}catch (HibernateException e) {
			if(tx!=null)
				tx.rollback();
			e.printStackTrace();
			throw e;
		}finally{
			HibernateUtil.closeSession();
		}
	}
}

  

4.测试结果

控制台信息:

 

数据库表信息:

 

posted @ 2017-04-06 22:56  chxbar  阅读(131)  评论(0编辑  收藏  举报