Java – use hibernate JPA to store objects in columns

Can I store things like the following that use only one table? Now, what hibernate will do is to create two tables, one for family and one for people I want to serialize the familymembers object into the database columns

@Entity(name = "family")
class Family{

    private final List<Person> familyMembers;

}

class Person{

   String firstName,lastName;
   int age;

}

Solution

This is a terrible design. I really don't recommend it (you should create another table), but it's possible

First, you need to use the byte [] attribute to save the serialized version of the people list stored in blob in the database So use @ lob to annotate its getter (I will make getter and setter private without exposing them) Then, expose the "false" getters and setters to return or set a list < person > from byte [] In the following example, I use serializationutils in common Lang (provide your own help class if you don't want to import this library) to serialize / deserialize in / from byte [] Don't forget to mark "false" with @ transaction or hibernate. Getter will try to create a field (and fail because it won't be able to determine the type of list)

@Entity(name = "family")
class Family implements Serializable {

    // ...

    private byte[] familyMembersAsByteArray;

    public Family() {}

    @Lob
    @Column(name = "members",length = Integer.MAX_VALUE - 1)
    private byte[] getFamilyMembersAsByteArray() { // not exposed
        return familyMembersAsByteArray;
    }

    private void setFamilyMembersAsByteArray((byte[] familyMembersAsByteArray() { // not exposed
        this.familyMembersAsByteArray = familyMembersAsByteArray;
    }

    @Transient
    public List<Person> getFamilyMembers() {
        return (List<Person>) SerializationUtils.deserialize(familyMembersAsByteArray);
    }

    public void setParticipants(List familyMembers) {
        this.familyMembersAsByteArray = SerializationUtils.serialize((Serializable) familyMembers);
    }
}

Don't forget to make the person class serializable and add a real serialVersionUID (I just show a default value here):

public class Person implements Serializable {

   private static final long serialVersionUID = 1L;

   // ...

   private String firstName,lastName;
   private int age;

}

However, let me insist that this is a terrible design and it will be very fragile (the person who changes may need to "migrate" the contents of the blob to avoid the deserialization problem, which will become painful. You should reconsider this idea and use another table instead (or I don't understand why you use the database)

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
分享
二维码
< <上一篇
下一篇>>