Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA @MapsId vs @JoinColumn(updatable=false, insertable=false)

Tags:

java

jpa

It seems to me that there is virtually no difference between the below two ways of mapping. Here is an example base on @MapsId javadoc:

// parent entity has simple primary key

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

// 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;
}

What if I change Dependent's mapping to:

@Entity
public class Dependent {
   @EmbeddedId DependentId id;

   @ManyToOne
   @JoinColumn("empid", insertable=false, updatable=false)
   Employee emp;
}

What is the difference of the above two approach?

like image 300
Adrian Shum Avatar asked Dec 13 '13 03:12

Adrian Shum


1 Answers

So, I tested @MapsId for my usage when in the table I have only one foregin key it was no different. But for tables where I have two foregin keys to one table like ... UserTable, and EmailTable-> @MapsId(owner)UserTable owner, @MapsId(receiver) UserTable receiver i have problems with that. Hibernate throws exceptions. So i have to back to old @JoinColumn way of doing that. That was a one differemce that I met with that adnotations.

like image 150
RMachnik Avatar answered Sep 19 '22 13:09

RMachnik