6.1 Store files on the server

Sometimes binary objects need to be saved to the database. For example, files. If the file is large, then it is most reasonable to store it in a separate folder on the disk, and store its paths in the database. Example:

c:\db-files\users\12355\avatar.jpg

And in the database we store just a relative path to the file:

\12355\avatar.jpg

It is convenient to store a relative path in the database, since it is then easy to get a URL from it:

https://storage.codegym.cc/users/12355/avatar.jpg

We just paste the relative path to the server name and we're done.

6.2 Store images directly in the database

However, if the pictures are small, they can be stored directly in the database and given to the client as a set of bytes. For such cases, SQL has a special BLOB data type - Binary Large Object. Or rather, there are even two of them:

  • CLOB - Character Large Object,
  • BLOB - Binary Large Object.

CLOB is used to store very large texts. A BLOB is for storing binary data, such as small pictures, videos, and the like.

Example:

@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 annotation @Lobtells Hibernate that a Large Object is stored in the field . And columnDefinition="BLOB"already talks about how to save it all in the database.

Let's write an example code that saves a new user and his photo to the database:

byte[] imageBuffer = Files.readAllBytes(Paths.get("C:/temp/avatar.png"))

User user = new User();
user.setId("1");
user.setName("Zapp");
user.setPhoto(imageBuffer);

session.persist(user);

6.3 XML and JSON

Hibernate has interesting support for JSON as a data type. It allows you to store a HashMap of strings as a single JSON object. If the DBMS can work with JSON, then it looks like this:

@JdbcTypeCode(SqlTypes.JSON)
private Map<String, String> properties;

Hibernate takes care that the type object Map<String, String>is serialized into a single JSON object. Also, when reading an object from the database, it turns the JSON object into a set of Map<String, String>.

Hibernate can do something similar with XML:

@JdbcTypeCode(SqlTypes.SQLXML)
private Map<String, String> properties;
undefined
1
Task
Module 4. Working with databases, level 12, lesson 5
Locked
Save audio file to database
task1205