Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to not generate setters and getters for @Id fields in JPA?

Assuming a JPA entity with (for example) an long id generated automatically:

@Entity
@AutoProperty
public class SomeItem {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)   
    private long Id;

    ...

}

Is there any reason to not generate setter and getters for this Id? One might be tempted to not generate a setter for example, since it is the responsibility of JPA to generate the ID.

like image 905
Jérôme Verstrynge Avatar asked Nov 27 '22 11:11

Jérôme Verstrynge


1 Answers

I see that other comments has misguided you so I feel myself obliged to elaborate on this issue a bit, even though I can't give you a scientific and complete answer. @vcetinick wrote the current accepted answer:

You may find that you may be able to get away [..] from the persistence side of things.

This quote in particular is wrong. All depends on where you put your @Id annotation. The specification says:

If the entity has field-based access, the persistence provider runtime accesses instance variables directly.

Thus you are not required in any way to provide a setter or getter. Because you annotated your field and not a getter method (annotating the setter method will be ignored and have no bearing).

However, if you write a getter method, and annotated this method with your @Id annotation instead of your field, then we would tell our persistence provider to access our field through the accessor (getter) and mutator (setter) methods and not use reflection. In that case, both a getter and a setter should be present. The book Pro JPA 2: Mastering the Java™ Persistence API writes on page 71 (bold markup by me!):

When property access mode is used, the same contract as for JavaBeans applies, and there must be getter and setter methods for the persistent properties. The type of property is determined by the return type of the getter method and must be the same as the type of the single parameter passed into the setter method. Both methods must be either public or protected visibility.

Therefore, I usually annotate my id field, and write both a setter and getter method, but the setter method I give protected access. I just don't want any other pieces of code to have easy write access to such an important field. I don't know if this would cause problems in other domains. I'm no expert. But I don't find any rationale either as to why not setup an id attribute in this way. See also the Netbeans forums.

like image 162
Martin Andersson Avatar answered Dec 09 '22 13:12

Martin Andersson