3
votes

Can anyone explain using an example as to why the @Transient annotation in JPA has @Target method as well?

I am referring to documentation http://docs.oracle.com/javaee/5/api/javax/persistence/Transient.html

@Target(value={METHOD,FIELD})

Thanks in advance!

3
you can access transient attribute by getter method or field, that's why it has - Saravana
How does it make sense to allow it on methods? allowing only on fields shouldn't be enough? - user2906555
no, you can program to access field using reflection or getter methods. - Saravana
That is nothing to do with JPA and just basic java annotations. - Neil Stockton

3 Answers

1
votes

In JPA entity you can annotate fields or methods (getters). The @Id annotation dictates this, meaning if you put @Id on a field then all your annotations should go on fields but if you put it on, for example, @Id Long getId() then other annotations should follow. That's why @Transient can be on a method as well.

For example, if you have this

@Id
private Long id;

@Transient
private String someTransientField;

private Long getId() {
    return this.id;
}

private String getSomeTransientField() {
    return this.someTransientField;
}

then someTransientField would be treated as transient. But if @Id would stay on the field, and you move @Transient to private String getSomeTransientField() then someTransientField would be treated as persistent, since @Id is on the field and therefore all other annotations are expected to be on fields as well.

So the case where @Transient would work on the method is this

private Long id;

private String someTransientField;

@Id
private Long getId() {
    return this.id;
}

@Transient
private String getSomeTransientField() {
    return this.someTransientField;
}
0
votes

@Target annotation lets you define where this annotation can be used, e.g., the class, fields, methods, etc. indicates which program element(s) can be annotated using instances of the annotated annotation type.

@Target(value={METHOD,FIELD}) means that the annotation can only be used on top of types (methods and fields typically).you can leave the target out all together so the annotation can be used for both classes, methods and fields.

In JPA @Target – Marks another annotation @Transient to restrict what kind of java elements the annotation may be applied to.

0
votes

It means the annotation can be used on Field or method.

If the field is annotated, the field will be accessed using reflection.

If method(getter) is annotated, then the getter method will be used to access it.