By default JPA uses Java serialization to persist properties of unknown Serializable
types (so that you have a serialized representation stored as a byte[]
).
Usually it's not what you want, because there can be more efficient ways to represent your data. For example, BitSet
can be efficiently represented as a number (if its size is limited), or byte[]
, or something else (unfortunately, BitSet
doesn't provide methods to do these conversions, therefore you need to implement them manually).
When you've decided what kind of data representation you want to have in the database you need to tell JPA to apply the necessary conversion. There are two options:
Implement conversion in getters and setters. For example, as follows:
@Entity
@Table(name = "myTable")
@Access(AccessType.FIELD)
public class MyClass {
...
@Transient // Do not store this field
protected BitSet tags;
@Access(AccessType.PROPERTY) // Store the property instead
@Column(name = "Tags")
byte[] getTagsInDbRepresentation() {
... // Do conversion
}
void setTagsInDbRepresentation(byte[] data) {
... // Do conversion
}
...
}
Use provider-specific extension to perform the conversion implicitly (for example, custom types in Hibernate). This approach allows you to reuse your type conversion logic in different entities.