且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可有人请给我解释一下@MapsId休眠?

更新时间:2023-11-09 23:30:10

下面是对象DB


  

指定一个多对一或一对一的关系属性,它提供了一个EmbeddedId主键,一个EmbeddedId主键中的属性,或父实体的一个简单的主键的映射。值元素指定了关系属性对应复合键中的属性。如果实体的主键是相同的Java类型由关系引用的实体的主密钥的,未指定的值属性


块引用>
  //母公司拥有简单的主键@实体
公共类Employee {
   @Id长EMPID;
   字符串名称;
   ...
}//依赖实体使用EmbeddedId复合键@Embeddable
公共类DependentId {
   字符串名称;
   长EMPID; //对应于员工的主键类型
}@实体
公共类相关{
   @EmbeddedId DependentId ID;
    ...
   @MapsId(EMPID)//映射嵌入的id属性EMPID
   @ManyToOne员工EMP;
}

阅读API文档这里。

Can someone please explain 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 ?

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.