Saving java BitSet for DB

Working with JPA, I would like to be able to save BitSet to the database and pull it back.

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 also define "columnDefinition"? I really don't understand how this is saved (using toString ()?) And, besides, how does it return the load from the database.

Could you help me with this?

Thank!

+5
source share
2 answers

By default, JPA uses Java serialization to store properties of unknown types Serializable(so you have a serialized view saved as byte[]).

, , . , BitSet ( ) byte[] - ( , BitSet , ).

, , JPA, . :

  • . , :

    @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
        }
        ...
    }
    
  • , (, Hibernate). .

+3

( int byte[]) :

@Entity
@Access(AccessType.FIELD)
public class SampleEntity {

    @Transient
    private IntBitSet isolationLevel = new IntBitSet(0);

    public static final int USER_BIT = 0;
    public static final int DEVICE_BIT = 1;
    // 2, 3, 4, ...

    public boolean isUserIsolated() {
        return isolationLevel.bitGet(USER_BIT);
    }

    public boolean isDeviceIsolated() {
        return isolationLevel.bitGet(DEVICE_BIT);
    }

    public void setUserIsolated(boolean b) {
        isolationLevel.bitSet(USER_BIT, b);
    }

    public void setDeviceIsolated(boolean b) {
        isolationLevel.bitSet(DEVICE_BIT, b);
    }

    @Access(AccessType.PROPERTY)
    @Column
    public int getIsolationLevel() {
        return isolationLevel.getValue();
    }

    public void setIsolationLevel(int isolationLevel) {
        this.isolationLevel = new IntBitSet(isolationLevel);
    }

    private static class IntBitSet {
        private int value;

        public IntBitSet(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        public boolean bitGet(int i) {
            return ((value >> i) & 1) == 1;
        }

        public void bitSet(int i, boolean b) {
            if (b) {
                bitSet(i);
            } else {
                bitUnset(i);
            }
        }
        private void bitSet(int i) {
            value = value | (1 << i);
        }
        private void bitUnset(int i) {
            value = value & ~(1 << i);
        }
    }
}
+4

All Articles