Assigning @MapsId annotation in Hibernate
I'm trying to figure out what's the difference in @MapsId annotation in Hibernate. I have looked at the Hibernate documentation but I am still confused by the explanations given here as I am new to Hibernate.
document says the following:
@Entity
class Customer {
@EmbeddedId CustomerId id;
boolean preferredCustomer;
@MapsId("userId")
@JoinColumns({
@JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
@JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
})
@OneToOne User user;
}
@Embeddable
class CustomerId implements Serializable {
UserId userId;
String customerNumber;
//implements equals and hashCode
}
@Entity
class User {
@EmbeddedId UserId id;
Integer age;
}
@Embeddable
class UserId implements Serializable {
String firstName;
String lastName;
//implements equals and hashCode
}
In the built-in id object, the association is represented as the identifier of the associated object. But you can tie your value to a regular association in essence through the @MapsId annotation. The @MapsId value matches the property name of the embedded identifier object that contains the corresponding object identifier. In a database, this means that the Customer.user and CustomerId.userId properties share the same base column (user_fk in this case).
I don't understand what this explanation says, so I got tired of hbm2ddl
being set like create
in my config file and I noticed the following:
With @MapsId and @JoinColumns on the Customer object, DDL statements are:
Hibernate: create table CUSTOMER (customerNumber varchar2(255 char) not null, preferredCustomer number(1,0) not null, userfirstname_fk varchar2(255 char) not null, userlastname_fk varchar2(255 char) not null, primary key (customerNumber, userfirstname_fk, userlastname_fk))
Hibernate: create table USER (firstName varchar2(255 char) not null, lastName varchar2(255 char) not null, age number(10,0), primary key (firstName, lastName))
Hibernate: alter table CUSTOMER add constraint UK_xxxx unique (userfirstname_fk, userlastname_fk)
Hibernate: alter table CUSTOMER add constraint FK_xxxx foreign key (userfirstname_fk, userlastname_fk) references TBL_USER
If I remove the @MapsId and @JoinColumns annotations, I see the following:
Hibernate: create table CUSTOMER (customerNumber varchar2(255 char) not null, firstName varchar2(255 char), lastName varchar2(255 char), preferredCustomer number(1,0) not null, user_firstName varchar2(255 char), user_lastName varchar2(255 char), primary key (customerNumber, firstName, lastName))
Hibernate: create table USER (firstName varchar2(255 char) not null, lastName varchar2(255 char) not null, age number(10,0), primary key (firstName, lastName))
Hibernate: alter table CUSTOMER add constraint FK_xxxx foreign key (user_firstName, user_lastName) references TBL_USER
Please help me understand the concept of @MapsId annotation in Hibernate.
source to share