使用 时,始终需要至少关联两个实体。假设我们有一个与该实体相关的实体( 具有 FK 到 )。Map
Owner
Car
Car
Owner
所以,将有一个:Owner
Map
Car(s)
Map<X, Car>
@MapKey
将为您提供用于将 a 分组到其 .例如,如果我们在 中有一个(车辆识别号)属性,我们可以将其用作键:@MapKey
Car's
Car
Owner
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;
}
这将按车轮驱动类型对汽车进行分组。
@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
需要第三个实体,比如说你有一个关联从 to 和 car 也有一个关联到 a ,这样你就可以按以下方式分组:@MapKeyJoinColumn
Manufacturer
Owner
Car
Manufacturer
Owner's
Cars
Manufacturer
@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;
}