0

I'm a JPA novice please stay with me, I need some help as I can't decide what option to use.

Option 1: I place the annotations above the entity fields and allow write access to the object only at creation time through the constructor (and then save it to the database). As I understand the JPA manager can still perform update queries since its field access (as stated hier). This way I have to create a new query if I want to update or change entries but then i have to create these queries myself (as stated hier).

Option 2: I place the annotations above the getters/setters and use the property access and then use the find Method of the Entity Manager together with the setter (like hier). This will create the query for me but now the setters allow to change the object after its creation (before I add it to the database).

My opinion Also while hier the top answer recommends to use setters

The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually

Hier the second answer (which has the most upvotes) states that field access is the way to go.

I'm confused but would probably use the second option together with a constructor and use the setters only for the Entity manager and making the setters package private.

Info

  • Im using eclipseLink 2.5+ as the persistence provider and JPA 2.0 with Java EE6
  • I should have mentioned that I work with SAPs Hana Cloud Platform and that there tutorial uses the first option with setters instead of a constructor.

Question: Should I use option 1 or 2 as a JPA novice and for a database only for logging purposes whose entries will be deleted after 1-30 days. ?

Community
  • 1
  • 1
  • 1
    See also http://stackoverflow.com/questions/4188048/why-should-anybody-put-annotations-on-the-getters-or-setters-when-using-jpa-to-m – perissf Feb 15 '17 at 13:53
  • I have read it before and it supports the second Option, now I see the specific access part but what would that change for my scenario? – MADforFUNandHappy Feb 15 '17 at 13:57

1 Answers1

1

IMHO you should take the 2nd approach. The entire point of ORM and JPA is to avoid having to deal with database and write queries. The negligible performance benefit of the 1st approach is not worth the trouble you will face in synchronization, readability and code maintenance.

Having said that, there may be scenarios that will warrant this hack. For example you wouldn't want the memory to be flooded with log objects, if all you do is perform write operations and never read. If you are not too sure about this then better use the 2nd approach

Monish Sen
  • 1,293
  • 2
  • 18
  • 29