Save Java BitSet to DB

Using JPA, I want to be able to save BitSet to the database and pull it back to the program

Suppose I have:

@Entity
@Table(name = "myTable")
public class MyClass {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Object_Id")
    protected long id;

    @Column(name = "Tags")
    protected BitSet tags;

... getters & setters etc...
}

Should "columndefinition" also be defined? I really don't understand how persistent it is (using tostring()?) And how it is loaded back from the database

Can you help me?

thank you!

Solution

By default, JPA uses Java serialization to store properties of unknown serializable types (so that the serialized representation is stored as byte [])

Usually it's not what you want, because there can be a more efficient way to represent your data For example, BitSet can be effectively represented as a number (if its size is bounded), or byte [], or something else (unfortunately, BitSet does not provide a method for these transformations, so you need to implement them manually)

When you decide which data representations you want to have in the database, you need to tell JPA to apply the necessary transformations There are two options:

>Implement the conversion in getter and setter For example:

@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 extensions to implicitly perform transformations (for example, custom types in Hibernate) This method allows you to reuse type transformation logic in different entities

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>