服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

在cmp实体bean中使用blob数据类型

  在oracle这样的关系数据库中,clob和blob类型被用来存放大对象。bolb表示二进制大对象,这种数据类型通过用来保存图片,图象,视频等。clob表示字符大对象,能够存放大量基于字符的数据。

  jdbc定义java类型java.sql.clob 和java.sql.blob 对应数据库中的clob和blob类型。然而这两种类型并不能在实体bean中使用,因为这两个类没有被序列化(serializable)。因此我们不能在cmp实体bean中定义java.sql.clob或java.sql.blob这两种数据类型。

  如果我们要使用数据库的blob字段,我们必须在实体bean中声明cmp字段为 byte[] 并映射该字段到数据库的blob字段。如果要使用clob字段,我们需要使用定义cmp字段为 java.lang.string or char[] 。

一个entity的范例
  在一个企业里,处于安全考虑,我们也许要将员工的图片保存到数据库中的表里。这里我们使用employeepicture 作为范例来代表员工的图片实体。这个employeepicturebean cmp有两个属性 empno, picture。 picture 字段被定义成byte[]型 。

  该employeepicture实体bean被映射到emppic数据表, picture 属性被映射为emppic 表中的picture 字段,该picture字段是定义为blob类型的。

  下面是employeepicturebean.java的部分核心代码:

public abstract class employeepicturebean implements entitybean
{
....
public abstract byte[] getpicture();
public abstract void setpicture(byte[] newpicture);
public long ejbcreate(long empno, byte[] newpicture)
{
setempno(empno);
setpicture(newpicture);
return empno;
}

public void ejbpostcreate(long empno, byte[] newpicture)
{
}
...
}



  如果我们使用oc4j 9.0.4 ,就需要在orion-ejb-jar.xml中定义实体bean属性到数据表字段的映射。如果使用了其他j2ee容器,就需要在相关厂商的部署描述符中定义o-r映射。下面演示在oc4j中的映射代码:

<entity-deployment name="employeepicture" data-source="jdbc/oracleds"
table="emppic">

<primkey-mapping>

<cmp-field-mapping name="empno" persistence-name="empno"
persistence-type="number(8)"/>

</primkey-mapping>

<cmp-field-mapping name="empno" persistence-name="empno"
persistence-type="number(8)"/>

<cmp-field-mapping name="picture" persistence-name="picture"
persistence-type="blob"/>

</entity-deployment>



客户端:
  cmp实体bean的客户端没有什么特别的处理。唯一需要注意的是在update数据表时要使用bufferedinputstream 来读取image文件,但在检索数据表时使用outputstream 。

  下面演示如何读取一个image文件,并创建一个bean实例:

// locate and open the file

file imgfile = new file(filename);

long imgfilesize= imgfile.length();

// initialize the byte array

byte bytevalue[] = new byte[(int)imgfilesize];

// read the file into the byte array

inputstream is = new bufferedinputstream(new fileinputstream(imgfile));

int len = is.read(bytevalue);

//add the byte to the entity bean field

if(len!=imgfilesize)

{

system.out.println("read bytes did not equal file size on directory");

}

else

{

employeepicturelocal employeepicture = emphome.create(empno , bytevalue);




结论
  我们不能在cmp实体bean中直接映射 java.sql.blob类型到数据库中的blob字段。而是要使用byte[]来操作blob数据类型。但是我们要值得注意的是,如果存储的数据非常大(超过25m),那么这种方式的处理效率将非常低,那时只能考虑其他可选的方案子。

  完整的代码范例可以从以下地址中得到:http://www.oracle.com/technology/tech/java/oc4j/904/how_to/how-to-ejb-cmpblob.zip



扫描关注微信公众号