Can someone please explain to me @MapsId
in hibernate? I'm having a hard time understanding it.
It would be great if one could explain it with an example and in what kind of use cases is it most applicable?
Annotation Type MapsId Designates a ManyToOne or OneToOne relationship attribute that provides the mapping for an EmbeddedId primary key, an attribute within an EmbeddedId primary key, or a simple primary key of the parent entity.
Yes, hibernate requires an Id. Sometimes if you are dealing with a legacy database that for whatever reason does not have a key, you can define the key in Hibernate to be a composite key of all the columns for example, as this will be guaranteed to be unique.
Hibernate will scan that package for any Java objects annotated with the @Entity annotation. If it finds any, then it will begin the process of looking through that particular Java object to recreate it as a table in your database!
Here is a nice explanation from Object DB.
Designates a ManyToOne or OneToOne relationship attribute that provides the mapping for an EmbeddedId primary key, an attribute within an EmbeddedId primary key, or a simple primary key of the parent entity. The value element specifies the attribute within a composite key to which the relationship attribute corresponds. If the entity's primary key is of the same Java type as the primary key of the entity referenced by the relationship, the value attribute is not specified.
// 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; }
Read the API Docs here.
I found this note also useful: @MapsId
in hibernate annotation maps a column with another table's column.
It can be used also to share the same primary key between 2 tables.
Example:
@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; ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With