Override @ManyToOne targetEntity for @Embedded with interfaces
I have used a workable solution to this for a while now, but it includes a minor case of vendor lock-in. I have found no way of doing this with JPA annotations only, but there is a Hibernate-specific annotation @Target
that does the trick. I have done something like you have, with the expected results. However, I didn't use your other annotations so I can't guarantee it will turn out to work as you expect.
Nothing strange going on in the Embeddable classes:
public interface PointsInt extends Serializable {
int offensivePoints();
int defensivePoints();
}
@Embeddable
public class Points implements PointsInt {
private int def;
private int off;
public int offensivePoints() { return off; }
public int defensivePoints() { return def; }
}
But in the consuming class, we use Hibernate's @Target
:
import javax.persistence.*;
import org.hibernate.annotations.Target;
@Entity
public class Series extends LongIdEntity implements Serializable {
@Embedded
@Target(Points.class)
private PointsInt points;
// I prefer to declare my annotations on fields rather than methods
}
Result:
mysql> describe series;
+-----------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| def | int(11) | YES | | NULL | |
| off | int(11) | YES | | NULL | |
+-----------------+-------------+------+-----+---------+----------------+
3 rows in set (0.12 sec)