I've a class that doesn't serialize very well to a relational entity. As so, I'd like to persist it using JPA as a CLOB (I can serialize it to a String). How would I do this using JPA?
Example Entity:
@Entity
@Table(name = "MY_TABLE")
public class Foo {
@Id
private Long id;
private String simpleString;
private Bar bar;
}
Bar is the class that I'd like persisted as a CLOB inside MY_TABLE.
You could annotate the string with javax.persistence.Lob
.
@Lob
@Basic(fetch = FetchType.LAZY)
private String simpleString;
See Lob
Javadoc:
Specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the
Basic
annotation or theElementCollection
annotation when the element collection value is of basic type. A Lob may be either a binary or character type.The
Lob
type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.
Next, you could set the Bar
field to transient
so it's not persisted:
@Transient
private Bar bar
Then in your Bar
getter, you could deserialise it if required:
public Bar getBar()
{
if (this.bar == null)
{
this.bar = deserialise(this.simpleString);
}
return this.bar;
}
Thread safety is left as an exercise for the reader.
Additionally, you could also use @PrePersist
to serialise Bar
into its string form if you needed to do this immediately prior to persisting.
I had a similar problem like you where I needed to store a JSON in a field so when I used BLOB I was causing myself a lot of unnecessary headaches. You are using blob for a content kind of data, I respectfully advise you to use CLOB for data if it's in Character format.
to wrap my answer up, if you are using the ORACLE database(which is a database that always causes problems of speaking its language) use bellow format as a guide or best practice, which is based on oracle documentation itself, to solve your problem:
@Lob @Basic(fetch=LAZY)
@Column(name="REPORT")
protected String report;
to retrieve data or persist data you can use spring Crudrepository
and use save
and findall
methods.
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With