2020-08-27

Hibernate JPA @Target Example

@Target

The @Target annotation is used to specify an explicit target implementation when the currently annotated association is using an interface type.

Target define an explicit target, avoiding reflection and generics resolving.

@Target mapping

The @Target annotation is used to specify the implementation class of a given association that is mapped via an interface. The @ManyToOne, @OneToOne, @OneToMany, and @ManyToMany feature a targetEntity attribute to specify the actual class of the entity association when an interface is used for the mapping.

The @ElementCollection association has a targetClass attribute for the same purpose.

However, for simple embeddable types, there is no such construct and so you need to use the Hibernate-specific @Target annotation instead.

Example :@Target mapping usage

public interface Coordinates {
double x();
double y();
}

@Embeddable
public static class GPS implements Coordinates {

private double latitude;

private double longitude;

private GPS() {
}

public GPS(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}

@Override
public double x() {
return latitude;
}

@Override
public double y() {
return longitude;
}
}

@Entity(name = "City")
public static class City {

@Id
@GeneratedValue
private Long id;

private String name;

@Embedded
@Target( GPS.class )
private Coordinates coordinates;

//Getters and setters omitted for brevity

}
The coordinates embeddable type is mapped as the Coordinates interface. However, Hibernate needs to know the actual implementation tye, which is GPS in this case, hence the @Target annotation is used to provide this information.

No comments:

Post a Comment