Photo by Jisun Han on Unsplash

Lazy loading images from database

@Lob
@Column(name = "file_content", columnDefinition = "LONGBLOB")
private byte[] content;
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>
@Lob
@Column(name = "file_content", columnDefinition = "LONGBLOB")
@Fetch(FetchMode.SELECT)
@Type(type="org.hibernate.type.MaterializedBlobType")
private byte[] content;
<plugin>
<groupId>org.hibernate.orm.tooling</groupId>
<artifactId>hibernate-enhance-maven-plugin</artifactId>
<version>${hibernate.version}</version>
<executions>
<execution>
<configuration>
<enableLazyInitialization>true</enableLazyInitialization>
</configuration>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
@Lob  
@Basic(fetch=FetchType.LAZY)
@Column(name = "file_content", columnDefinition = "LONGBLOB")
public Blob getFieldBlob() {
return content;
}
public void setFieldBlob(final Blob blobContent) {
this.content = blobContent;
}
@Transient
public String getField() {
if (getFieldBlob() == null){
return null;
}

try {
return MyOwnUtils.readStream(getFieldBlob().getCharacterStream());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void setField(final String field)
{
this.fieldBlob = Hibernate.createBlob(field);
}
@MappedSuperclass
public class BaseAttachment {

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "id")
private String id;

@NotBlank
@Column(name = "name", nullable = false)
private String name;

@NotBlank
@Column(name = "file_type", nullable = false)
private String fileType;
}
@Entity
@Table(name = "attachment")
public class AttachmentSummary extends BaseAttachment {
}
@Entity
@Table(name = "attachment")
public class Attachment extends BaseAttachment {

@Lob
@Column(name = "data", nullable = false, columnDefinition = "LONGBLOB")
private byte[] data;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store