一尘不染

JPA和Hibernate中@ MapKey,@ MapKeyColumn和@MapKeyJoinColumn之间的区别

hibernate

根据Hibernate文档,如果我们要将Map用作实体之间的关联,则有多个注释可用。医生说:

或者,将映射键映射到一个或多个专用列。为了自定义映射,请使用以下注释之一:

@MapKeyColumn(如果地图关键字是基本类型)。如果未指定列名,则使用属性名称,下划线和KEY(例如orders_KEY)。@MapKeyEnumerated
/ @MapKeyTemporal(如果地图键类型分别是枚举或日期)。@ MapKeyJoinColumn / @
MapKeyJoinColumns(如果地图键类型是另一个实体)。@ AttributeOverride / @
AttributeOverride当地图关键字是可嵌入对象时。使用密钥。作为可嵌入对象属性名称的前缀。如果您不使用泛型,也可以使用@MapKeyClass定义键的类型。

通过执行一些示例,我能够理解@MapKey仅用于将键映射到目标实体的属性,并且该键仅用于获取记录。@MapKeyColumn用于将键映射到目标实体的属性,并且该键用于保存以及获取记录。请让我知道这是否正确吗?

另外,请告诉我何时需要使用@ MapKeyJoinColumn / @ MapKeyJoinColumns和@MapKeyEnumerated /
@MapKeyTemporal

谢谢!


阅读 1202

收藏
2020-06-20

共1个答案

一尘不染

使用a时,Map您始终需要关联至少两个实体。假设我们有一个Owner与该Car实体相关的实体(Car具有FK Owner)。

所以,Owner就有了MapCar(s)

Map<X, Car>

@MapKey

@MapKey会给你Car's用来集团的物业CarOwner。例如,如果我们在中具有vin(车辆识别号)属性Car,则可以将其用作carMap键:

@Entity
public class Owner {
    @Id
    private long id;

    @OneToMany(mappedBy="owner")
    @MapKey(name = "vin")
    private Map<String, Car> carMap;
}

@Entity
public class Car {
    @Id
    private long id;

    @ManyToOne
    private Owner owner;

    private String vin;

}

@MapKeyEnumerated

@MapKeyEnumerated会使用枚举从Car,像WheelDrive

@Entity
public class Owner {
    @Id
    private long id;

    @OneToMany(mappedBy="owner")
    @MapKeyEnumerated(EnumType.STRING)
    private Map<WheelDrive, Car> carMap;
}

@Entity
public class Car {
    @Id
    private long id;

    @ManyToOne
    private Owner owner;

    @Column(name = "wheelDrive")
    @Enumerated(EnumType.STRING)
    private WheelDrive wheelDrive;

}

public enum WheelDrive {
    2WD, 
    4WD;             
}

这将根据其WheelDrive类型对汽车进行分组。

@MapKeyTemporal

@MapKeyTemporal会使用Date/ Calendar场进行分组,像createdOn

@Entity
public class Owner {
    @Id
    private long id;

    @OneToMany(mappedBy="owner")
    @MapKeyTemporal(TemporalType.TIMESTAMP)
    private Map<Date, Car> carMap;
}

@Entity
public class Car {
    @Id
    private long id;

    @ManyToOne
    private Owner owner;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="created_on")
    private Calendar createdOn;         
}

@MapKeyJoinColumn

@MapKeyJoinColumn需要第三个实体,就像Manufacturer让你从这样一个联合体Owner,以Car与汽车也已经关联到Manufacturer,让您可以将所有Owner's
CarsManufacturer

@Entity
public class Owner {
    @Id
    private long id;

    @OneToMany(mappedBy="owner")
    @MapKeyJoinColumn(name="manufacturer_id")
    private Map<Manufacturer, Car> carMap;
}

@Entity
public class Car {
    @Id
    private long id;

    @ManyToOne
    private Owner owner;

    @ManyToOne
    @JoinColumn(name = "manufacturer_id")
    private Manufacturer manufacturer;          
}

@Entity
public class Manufacturer {
    @Id
    private long id;

    private String name;
}
2020-06-20