user2906555
user2906555

Reputation: 63

Why JPA Transient annotation have method in Target?

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!

Upvotes: 3

Views: 956

Answers (3)

Predrag Maric
Predrag Maric

Reputation: 24423

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;
}

Upvotes: 2

Saravana
Saravana

Reputation: 12817

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.

Upvotes: 0

Mihir
Mihir

Reputation: 581

@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.

Upvotes: 0

Related Questions