How to save java.util.Set via JPA?

I have an aliases field of type java.util.Set in one Entity . This Set does not mean anything to the entity.

  • How to save this aliases field via JPA?

  • How is this field stored in the database? I think this field is a multi-valued attribute for a database.

+4
source share
1 answer

How can I save this alias field through JPA?

JPA 1.0 does not support collections of base types, so you have to either:

  • Enter an entity and display it as @OneToMany ~ or ~
  • Get your Set stored in BLOB (as Serializable ) ~ or ~
  • Mark it with @Transient and use a different getter / setter to save it using a custom string representation (using a delimiter) ~ or ~
  • Use the extension of your JPA provider that supports the collection of base types (for example, Hibernate has the @CollectionOfElements annotation).

Solution # 1 will be the cleanest portable solution. Solution # 2 can lead to some problems during the upgrade. Solution # 3 is an ugly workaround for # 2. Solution # 4 is clean, but not portable.

JPA 2.0 has the @ElementCollection annotation for this use case (this is of course the perfect solution).

How this field is stored in the database

Depending on the chosen implementation, it may be in the BLOB in VARCHAR in another table.

+7
source

Source: https://habr.com/ru/post/1307214/


All Articles