Mapping LOB Data in Hibernate – 在Hibernate中映射LOB数据

最后修改: 2018年 3月 20日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

LOB or Large OBject refers to a variable length datatype for storing large objects.

LOB或Large OBject是指一种用于存储大型对象的可变长度数据类型。

The datatype has two variants:

该数据类型有两种变体。

  • CLOB – Character Large Object will store large text data
  • BLOB – Binary Large Object is for storing binary data like image, audio, or video

In this tutorial, we’ll show how we can utilize Hibernate ORM for persisting large objects.

在本教程中,我们将展示如何利用Hibernate ORM来持久化大型对象。

2. Setup

2.设置

For example, we’ll use Hibernate 5 and H2 Database. Therefore we must declare them as dependencies in our pom.xml:

例如,我们将使用Hibernate 5和H2数据库。因此,我们必须在我们的pom.xml中声明它们为依赖项:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.12.Final</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.196</version>
</dependency>

The latest version of the dependencies is in Maven Central Repositories.

最新版本的依赖项在Maven Central Repositories

For a more in-depth look at configuring Hibernate please refer to one of our introductory articles.

关于配置Hibernate的更深入研究,请参考我们的介绍性的文章之一。

3. LOB Data Model

3.LOB数据模型

Our model “User” has id, name, and photo as properties. We’ll store an image in the User‘s photo property, and we will map it to a BLOB:

我们的模型“User”有id、name和photo作为属性。我们将在User的照片属性中存储一张图片,并将其映射到一个BLOB。

@Entity
@Table(name="user")
public class User {

    @Id
    private String id;
	
    @Column(name = "name", columnDefinition="VARCHAR(128)")
    private String name;
	
    @Lob
    @Column(name = "photo", columnDefinition="BLOB")
    private byte[] photo;

    // ...
}

The @Lob annotation specifies that the database should store the property as Large Object. The columnDefinition in the @Column annotation defines the column type for the property.

@Lob 注解指定了数据库应该将该属性存储为大对象@Column注解中的columnDefinition定义了该属性的列类型。

Since we’re going to save byte array, we’re using BLOB.

因为我们要保存字节数组,所以我们要使用BLOB.

4. Usage

4.使用方法

4.1. Initiate Hibernate Session

4.1.启动Hibernate会话

session = HibernateSessionUtil
  .getSessionFactory("hibernate.properties")
  .openSession();

Using the helper class, we will build the Hibernate Session using the database information provided in hibernate.properties file.

使用辅助类,我们将使用hibernate.properties文件中提供的数据库信息构建Hibernate Session

4.2. Creating User Instance

4.2.创建用户实例

Let’s assume the user uploads the photo as an image file:

我们假设用户将照片作为一个图像文件上传。

User user = new User();
		
InputStream inputStream = this.getClass()
  .getClassLoader()
  .getResourceAsStream("profile.png");

if(inputStream == null) {
    fail("Unable to get resources");
}
user.setId("1");
user.setName("User");
user.setPhoto(IOUtils.toByteArray(inputStream));

We convert the image file into the byte array by using the help of Apache Commons IO library, and finally, we assign the byte array as part of the newly created User object.

我们通过使用Apache Commons IO库的帮助,将图像文件转换为字节数组,最后,我们将字节数组作为新创建的User对象的一部分。

4.3. Persisting Large Object

4.3.持久大对象

By storing the User using the Session, the Hibernate will convert the object into the database record:

通过使用Session存储UserHibernate将把该对象转换成数据库记录。

session.persist(user);

Because of the @Lob annotation declared on the class User, Hibernate understands it should store the “photo” property as BLOB data type.

由于在User类上声明的@Lob注解,Hibernate理解它应该将“photo”属性存储为BLOB数据类型。

4.4. Data Validation

4.4.数据验证

We’ll retrieve the data back from the database and using Hibernate to map it back to Java object to compare it with the inserted data.

我们将从数据库中检索数据,并使用Hibernate将其映射回Java对象,与插入的数据进行比较。

Since we know the inserted Users id, we will use it to retrieve the data from the database:

由于我们知道插入的User s id,我们将使用它从数据库中检索数据。

User result = session.find(User.class, "1");

Let’s compare the query’s result with the input User‘s data:

让我们把查询的结果与输入的User的数据进行比较。

assertNotNull(
  "Query result is null", 
  result);
 
assertEquals(
  "User's name is invalid", 
  user.getName(), result.getName() );
 
assertTrue(
  "User's photo is corrupted", 
  Arrays.equals(user.getPhoto(), result.getPhoto()) );

Hibernate will map the data in the database to the Java object using the same mapping information on the annotations.

Hibernate将使用注释上的相同映射信息将数据库中的数据映射到Java对象。

Therefore the retrieved User object will have the same information as the inserted data.

因此,检索到的User对象将具有与插入的数据相同的信息。

5. Conclusion

5.结论

LOB is datatype for storing large object data. There’re two varieties of LOB which is called BLOB and CLOB. BLOB is for storing binary data, while CLOB is for storing text data.

LOB是用于存储大型对象数据的数据类型。有两种类型的LOB叫做BLOBCLOBBLOB用于存储二进制数据,而CLOB则用于存储文本数据。

Using Hibernate, we have demonstrated how it’s quite easy to map the data to and from Java objects, as long as we’re defining the correct data model and the appropriate table structure in the database.

使用Hibernate,我们已经证明了将数据映射到Java对象或从Java对象中映射出来是多么容易,只要我们在数据库中定义了正确的数据模型和适当的表结构。

As always the code for this article is available over on GitHub.

像往常一样,本文的代码可在GitHub上获得