Mark non db fields @Transient vs extent JPA Entity?

情到浓时终转凉″ 提交于 2020-08-08 17:16:27

问题


We have a JPA Entity. Once the entity is persisted in db, some fields of this entity(db columns) along with some other data (which is not part of this entity) has to be stored in a JCR object-store.

Should I create one single Entity(JPA) for both DB and JCR and just add JCR fields in Entity and mark them @Transient?

or

Should I use inheritance or composition(using JPA Entity) and create a new JCR specific object? Basically, should JPA entities be strictly used for DB or is @Transient in this case an abuse?


回答1:


should JPA entities be strictly used for DB or is @Transient in this case an abuse?

Not an abuse but you will need to tread very carefully with JPA operations. One merge or refresh too many and your transient field value is lost.

Personally I'd create another layer of abstraction over both JPA and JCR that would manage your domain object as POJOs, some sort of DomainObjectRepository that would handle CRUD operations, interacting with both JPA and JCR, and encapsulating the mapping from/to both storage technologies (with mapping layer to each technology having a dedicated set of objects - JPA entities, JCR nodes).




回答2:


In my opinion, it is better to create two classes, one for the JPA entity, and one for JCR.

By separating both ambits, you have a better understanding and control of what must be done in order to process or persist every kind of object, and by focusing in a single concern, this two classes and the related logic are more robust and less error prone.

These two classes can define several common fields.

You can use tools such as MapStruct or Dozer to map fields between instances of the two classes.

Moreover, both classes can implement a common interface, with the common fields that they share, for instance, so you can reuse it in your logic (for audit purposes, implementing a Builder pattern, etcetera) if needed.



来源:https://stackoverflow.com/questions/62888268/mark-non-db-fields-transient-vs-extent-jpa-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!