bun*_*112 6 java hibernate jpa java-ee
在纯Hibernate我可以做:
Blob blob= Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(inputStream, len);
Run Code Online (Sandbox Code Playgroud)
如何在jpa中执行此操作(以hibernate作为提供程序)?
在纯hibernate中,我为blob创建了用户类型,它使用了setBinaryStream预处理语句.这个解决方案对我很有用,我正在寻找一种方法将它移植到JPA.
您可以在持久属性(Annotation Lob)上使用@Lob注释:
@Entity
public class MyEntity {
private byte[] content;
...
@Lob
public byte[] getContent() {
return content;
}
public void setContent(byte[] newContent) {
this.content = newContent;
}
}
Run Code Online (Sandbox Code Playgroud)
在您的代码中,您可以使用如下代码转换byte []中的流:
@Transient
public void setContentFromInputStream(InputStream is) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int l = 0;
do {
l = is.read(buff);
if (l > 0)
{
baos.write(buff, 0, l);
}
} while (l > 0);
is.close();
baos.flush();
baos.close();
content = baos.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)
@Lob注释也可以与String一起使用,在这种情况下,您将在DB上获得CLOB
您必须注意byte []的大小以避免OutOfMemoryError.
要仅使用流,您必须依赖于特定的jdbc供应商实现.例如,如果您使用的是Hibernate> = 3.6,则可以将它们的MyEntity.content类型更改为Blob并写入:
MyEntity entity = new MyEntity();
Session session = (Session)entityManager.getDelegate();
Blob newContent = session.getLobHelper().createBlob(inputStream, len);
entity.setContent(newContent);
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮到你
| 归档时间: |
|
| 查看次数: |
5937 次 |
| 最近记录: |