0% found this document useful (0 votes)
9 views7 pages

Hibernate Custom Data Type - Blob Type Example

The document provides an example of defining a custom data type in Hibernate using a Blob type for storing images and files. It includes code snippets for creating the custom ImageType class and using it in a Hibernate entity class. The example illustrates how to implement methods for retrieving and setting Blob data in a database context.

Uploaded by

gs23133
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views7 pages

Hibernate Custom Data Type - Blob Type Example

The document provides an example of defining a custom data type in Hibernate using a Blob type for storing images and files. It includes code snippets for creating the custom ImageType class and using it in a Hibernate entity class. The example illustrates how to implement methods for retrieving and setting Blob data in a database context.

Uploaded by

gs23133
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

06/12/2024, 19:19 Hibernate custom data type : Blob type example

800+ Q&As Menu Contact & reviews Register Login

800+ Big Data & Java Interview FAQs


It pays to prepare & choose from 2-6 offers. Read & Write more code to fast-track & go places with confidence.

Select A to Z of Java & Big Data Techs


search here … Go

Home Why?  Career  Membership 

Home › Quick Prep Java Interview › 150+ Spring & Hibernate FAQs › Framework - Hibernate Q&As › 12:

Hibernate custom data type : Blob type example

12: Hibernate custom data 300+ Java Interview


Q&As - Quick Prep FAQs

type : Blob type example 300+ Java Interview FAQs 📌 


150+ Spring & Hibernate
FAQs 
 Posted on January 7, 2015
150+ Java Architect FAQs 📌 

There are times you want to define a custom data type in Hibernate. 100+ Java code quality Q&As

Here is an example of using a custom ImageType defined as a Blob 150+ Java coding Q&As

databse type to store images, excel files, etc.

Step 1: Define the custom Hibernate data type “ImageTpe” as shown


below. 300+ Big Data Interview
Q&As - Quick Prep FAQs

1 300+ Big Data Interview


2 package com.myapp.common; FAQs 📌 

3
250+ Scala Interview FAQs 
4 import java.io.ByteArrayOutputStream;
5 import java.io.IOException; 250+ Python interview
6 import java.io.InputStream; FAQs 📌 
7 import java.io.Serializable;
8 import java.sql.Blob;
9 import java.sql.PreparedStatement;
10 import java.sql.ResultSet;
11 import java.sql.SQLException; Key Areas & Companion
12 import java.sql.Types; Techs FAQs
13 import java.util.Arrays;
14 16+ Tech Key Areas FAQs 
15 import org.hibernate.HibernateException;
16 import org.hibernate.engine.spi.SessionImplementor; 10+ Companion Tech Q&As 
17 import org.hibernate.usertype.UserType;
18
19 public class ImageType implements UserType
20 {
21
22 @Override

https://www.java-success.com/hibernate-custom-data-type-blob-type-example/ 1/7
06/12/2024, 19:19 Hibernate custom data type : Blob type example
23 public int[] sqlTypes() 800+ Enterprise & Core
24 { Java Q&As
25 return new int[]
26 {Types.BLOB
300+ Core Java Q&As 
27 };
28 } 300+ Enterprise Java Q&As 
29
30 @Override
31 public Class<Blob> returnedClass()
32 {
33 return Blob.class; Java & Big Data Tutorials
34 }
35
Tutorials - Golang 
36 @Override
37 public Object nullSafeGet(ResultSet rs, String[] names, Tutorials - Big Data 
38 throws HibernateException, SQLException
39 { Tutorials - Enterprise Java 
40 return getBlobFromBinaryStream(rs, names[0]);
41 }
42
43 private byte[] getBlobFromBinaryStream(ResultSet rs, St
44 throws SQLException
45 {
46
47 byte[] theBuff = new byte[2 * 1024];
48 InputStream theInStream = rs.getBinaryStream(aColNam
49
50 ByteArrayOutputStream theBaos = new ByteArrayOutputS
51 int n = 0;
52 try
53 {
54 if (theInStream != null)
55 {
56 while (-1 != (n = theInStream.read(theBuff))
57 {
58 theBaos.write(theBuff, 0, n);
59 }
60 }
61 theBaos.flush();
62 }
63 catch (IOException e)
64 {
65 e.printStackTrace();
66 }
67
68 return theBaos.toByteArray();
69 }
70
71 @Override
72 public void nullSafeSet(PreparedStatement stmt, Object a
73 throws HibernateException, SQLException
74 {
75 stmt.setBytes(aIndex, (byte[]) aValue);
76 }
77
78 @Override
79 public boolean equals(Object obj, Object other)
80 {
81 if ((obj == other) ||
82 (obj != null && other != null && Arraothers

https://www.java-success.com/hibernate-custom-data-type-blob-type-example/ 2/7
06/12/2024, 19:19 Hibernate custom data type : Blob type example
83 ((byte[]) obj),
84 ((byte[]) other))))
85 {
86 return true;
87 }
88 return false;
89 }
90
91 @Override
92 public int hashCode(Object obj) throws HibernateExceptio
93 {
94 return obj.hashCode();
95 }
96
97 @Override
98 public boolean isMutable()
99 {
100 return false;
101 }
102
103 @Override
104 public Object assemble(Serializable aSerializableObject
105 {
106 return null;
107 }
108
109 @Override
110 public Serializable disassemble(Object onj) throws Hibe
111 {
112 return null;
113 }
114
115 @Override
116 public Object replace(Object obj1, obj2, Object obj3) th
117 {
118 return null;
119 }
120
121 @Override
122 public Object deepCopy(Object obj)
123 {
124 return obj;
125 }
126 }
127
128

Step 2: Use the custom data type as shown below in Hibernate


entity.

1
2 package com.myapp.model.images;
3
4 import java.util.Date;
5
6 import javax.persistence.AttributeOverride;

https://www.java-success.com/hibernate-custom-data-type-blob-type-example/ 3/7
06/12/2024, 19:19 Hibernate custom data type : Blob type example
7 import javax.persistence.AttributeOverrides;
8 import javax.persistence.Column;
9 import javax.persistence.Entity;
10 import javax.persistence.EnumType;
11 import javax.persistence.Enumerated;
12 import javax.persistence.NamedQueries;
13 import javax.persistence.NamedQuery;
14 import javax.persistence.Table;
15
16 import org.hibernate.annotations.SQLDelete;
17 import org.hibernate.annotations.Type;
18 import org.hibernate.annotations.Where;
19
20 @Entity
21 @Table(name = "images", schema = "dbo", catalog = "my_catalog
22 @Where(clause = "inactiveFlag = 'N'")
23 @SQLDelete(sql = "UPDATE MyImages SET inactiveFlag = 'Y' WHER
24
25 public class MyImages
26 {
27
28 private static final long serialVersionUID = 1L;
29
30 public enum Status
31 {
32 PENDINDING_RELEASE, RELEASED;
33 }
34
35 private String name;
36 private byte[] image = new byte[0];
37 private Status status;
38 private byte[] timestamp;
39
40
41 public MyImages()
42 {
43 }
44
45 @Column(name = "name", nullable = false, length = 100)
46 public String getName()
47 {
48 return name;
49 }
50
51 public void setName(String name)
52 {
53 this.name = name;
54 }
55
56 //custom type
57 @Type(type = "com.myapp.common.ImageType")
58 @Column(name = "rules", nullable = false)
59 public byte[] getImage()
60 {
61 return image;
62 }
63
64 public void setImage(byte[] image)
65 {
66 this.image = image;

https://www.java-success.com/hibernate-custom-data-type-blob-type-example/ 4/7
06/12/2024, 19:19 Hibernate custom data type : Blob type example
67 }
68
69 @Enumerated(EnumType.STRING)
70 @Column(name = "Status", nullable = false, length = 30)
71 public Status getStatus()
72 {
73 return status;
74 }
75
76 public void setStatus(Status status)
77 {
78 this.status = status;
79 }
80
81 @Version
82 @Column(name = "Timestamp", insertable = false, updatable
83 @Generated(GenerationTime.ALWAYS)
84 public byte[] getTimestamp() {
85 return timestamp;
86 }
87
88
89 public void setTimestamp(byte[] timestamp) {
90 this.timestamp = timestamp;
91 }
92 }
93
94

‹ Java OpenCSV tutorial to work with CSV files

07: Hibernate mistakes – accessing objects outside of a transaction ›

About Latest Posts

Arulkumaran Kumaraswamipillai
Mechanical Engineer to self-taught Java engineer in 1999. Contracting since 2002 as a Java Engineer &
Architect and since 2016 as a Big Data Engineer & Architect. Preparation & key know-hows empowered me
to attend 150+ job interviews, choose from 130+ job offers & negotiate better contract rates. Author of the
book "Java/J2EE job interview companion", which sold 35K+ copies & superseded by this site with 3.5K+
registered users Amazon.com profile | Reviews | LinkedIn | LinkedIn Group | YouTube Email: java-
[email protected]

How to take the road less travelled?


Practicing & brushing up a few Q&As each day on broad number of main stream categories can make a huge impact in 3-12
months.

https://www.java-success.com/hibernate-custom-data-type-blob-type-example/ 5/7
06/12/2024, 19:19 Hibernate custom data type : Blob type example

"You are paid to read & write lots of code & solve business problems in a
collaborative environment"
100+ Free Java Interview FAQs
100+ Free Big Data Interview FAQs
Don't be overwhelmed by the number of Q&As. Job interviews are not technical contests to see who gets most number of questions right.
Nobody knows everything. The Clarity of the answers you give with real-life examples will go a long way in getting you multiple job offers.
It pays to brush-up & choose from 2-6 job offers. Experienced interviewers can easily judge your real experience from a few open-ended
questions & the answers you provide.

If you are pressed for time, popular categories are pinned 📌


for you to prioritise based on the job description. Here are my top career
making know-hows & tips to open more doors as a Java/Big Data Engineer, Architect or Contractor.

1. Feeling stagnated?
2. How to earn more?
3. Freelancing Vs contracting?
4. Self-taught professional?
5. Job Interview Tips
6. Resume Writing Tips

Top 12 popular posts last 30 days


300+ Java Interview Q&As with code, scenarios & FAQs
300+ Core Java Interview Q&As 01. Ice breaker Tell us about yourself? 02. Ice Breaker 8 Java real life scenarios…
(6,825)

300+ Big Data Interview Q&As with code, scenarios & FAQs
100+ SQL Interview Q&As 01. 50+ SQL scenarios based interview Q&As – What is wrong with this SQL code? 02.…
(2,425)

00: Top 50+ Core Java interview questions & answers for 1 to 3 years experience
Top 50 core Java interview questions covering core Java concepts with diagrams, code, examples, and scenarios. If you don't get…
(1,971)

Java 8 String streams and finding the first non repeated character with functional programming
Q1.Find the first non repeated character in a given string input using Java 8 or later? A1.Extends Find the first…
(1,669)

18 Java scenarios based interview Q&As for the experienced – Part 1


Let's look at scenarios or problem statements & how would you go about handling those scenarios in Java. These scenarios…
(1,541)

Membership Levels
Membership prices listed below are in Australian Dollars (A$). If you purchase in other currencies like Indian rupees, the equivalent…
(718)

30+ Java Code Review Checklist Items


This Java code review checklist is not only useful during code reviews, but also to answer an important Java job…
(524)

https://www.java-success.com/hibernate-custom-data-type-blob-type-example/ 6/7
06/12/2024, 19:19 Hibernate custom data type : Blob type example

8 real life Java scenarios with Situation-Action-Result (i.e. SAR) technique


The SAR (Situation-Action-Result) technique is very useful to tackle open-ended questions like: 1. What were some of the challenges you…
(522)

01: 30+ Java architect interview questions & answers – Part 1


One of the very frequently asked open-ended interview questions for anyone experienced is: Can you describe the high-level architecture of…
(480)

15 Ice breaker interview Q&As asked 90% of the time


Most interviews start with these 15 open-ended questions. These are ice breaker interview questions with no right or wrong answers…
(412)

0: 50+ SQL scenarios based interview Q&As – What is wrong with this SQL code?
This extends 18+ SQL best practices & optimisation interview Q&As. You can practice these SQLs by setting up the data…
(370)

02: 10 Java String class interview Q&As


Java Collection interview questions and answers and Java String class interview questions and answers are must know for any Java…
(357)

Disclaimer
The contents in this Java-Success are copyrighted and from EmpoweringTech pty ltd. The EmpoweringTech pty ltd has the right to correct or enhance the current content without

any prior notice. These are general advice only, and one needs to take his/her own circumstances into consideration. The EmpoweringTech pty ltd will not be held liable for any

damages caused or alleged to be caused either directly or indirectly by these materials and resources. Any trademarked names or labels used in this blog remain the property of

their respective trademark owners. Links to external sites do not imply endorsement of the linked-to sites. Privacy Policy

© 2024 800+ Big Data & Java Interview FAQs Responsive WordPress Theme powered by CyberChimps

Top

https://www.java-success.com/hibernate-custom-data-type-blob-type-example/ 7/7

You might also like