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

Viewed 11563

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?

2 Answers

I am using combination of both @MapsId and @JoinColumn together to avoid getting extra field getting created in DB for associating the entities. IF I ignore @JoinColumn, an extra field is getting created in DB.

@Entity
public class BookingsModel implements Serializable {

    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private SlotDateModel slotDateModelObj;

    @JsonProperty
    String slotnumber;

    @MapsId("memberid")
    @JsonBackReference
    @ManyToOne
    @JoinColumn(name="memberid",referencedColumnName = "memberid")
    @NotNull
    MemberModel memberModel;
.
.
.
}

@Entity
public class MemberModel implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @JsonProperty
    @Id
    String memberid;

    @JsonProperty
    String name;

    @JsonIgnore
    String phoneno;

    @JsonManagedReference
    @OneToMany
    Set<BookingsModel> bookings;
    .
    .
    .
    }

@Embeddable
public class SlotDateModel implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    String memberid;

    String slotdate;
.
.
.
}

Tables generated with @JoinColumn

Tables generated with @JoinColumn

Table generated when @JoinColumn is commented Can notice that the extra field "member_model_memberid" is getting added.

Table generated when @JoinColumn is commented

Related