2012-03-29 6 views

Antwort

19

Hier ist eine schöne Erklärung von Object DB.

Bezeichnet ein ManyToOne oder OneToOne Beziehung Attribut, das die Zuordnung für einen EmbeddedId Primärschlüssel, ein Attribut innerhalb eines EmbeddedId Primärschlüssels oder einen einfachen Primärschlüssel der übergeordneten Einheit zur Verfügung stellt. Das value-Element gibt das Attribut innerhalb eines zusammengesetzten Schlüssels an, dem das Beziehungsattribut entspricht. Wenn der Primärschlüssel der Entität denselben Java-Typ aufweist wie der Primärschlüssel der Entität, auf die die Beziehung verweist, wird das Attribut value nicht angegeben.

// parent entity has simple primary key 

@Entity 
public class Employee { 
    @Id long empId; 
    String name; 
    ... 
} 

// dependent entity uses EmbeddedId for composite key 

@Embeddable 
public class DependentId { 
    String name; 
    long empid; // corresponds to primary key type of Employee 
} 

@Entity 
public class Dependent { 
    @EmbeddedId DependentId id; 
    ... 
    @MapsId("empid") // maps the empid attribute of embedded id 
    @ManyToOne Employee emp; 
} 

die API Docs hier lesen.

1

Ich fand diese Notiz auch nützlich: @MapsId in Hibernate Annotation bildet eine Spalte mit einer anderen Tabelle Spalte.

Es kann auch verwendet werden, um den gleichen Primärschlüssel zwischen 2 Tabellen zu teilen.

Beispiel:

@Entity 
@Table(name = "TRANSACTION_CANCEL") 
public class CancelledTransaction { 
    @Id 
    private Long id; // the value in this pk will be the same as the 
        // transaction line from transaction table to which 
        // this cancelled transaction is related 

    @OneToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "ID_TRANSACTION", nullable = false) 
    @MapsId 
    private Transaction transaction; 
    .... 
} 

@Entity 
@Table(name = "TRANSACTION") 
@SequenceGenerator(name = "SQ_TRAN_ID", sequenceName = "SQ_TRAN_ID") 
public class Transaction { 
    @Id 
    @GeneratedValue(generator = "SQ_TRAN_ID", strategy = GenerationType.SEQUENCE) 
    @Column(name = "ID_TRANSACTION", nullable = false) 
    private Long id; 
    ... 
}