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:


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


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


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.


public class User {

    private String id;

	@Column(name = "name", columnDefinition="VARCHAR(128)")
    private String name;

	@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();


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:

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:

private Map<String, String> properties;