@MapKey与@MapKeyColumn二者区别

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/qq_37022150/article/details/77486311

不废话,对二者直接进行比较

@MapKey

先看2个实例:

Example 1:

  • @Entity
  • public class Department {
  • @OneToMany(mappedBy=”department”)
  • @MapKey // map key is primary key
  • public Map<Integer, Employee> getEmployees() {… }
  • }
    *
  • @Entity
  • public class Employee {
  • @Id Integer getEmpId() { … }
  • @ManyToOne
  • @JoinColumn(name=”dept_id”)
  • public Department getDepartment() { … }
  • }
    *
  • Example 2:
    *
  • @Entity
  • public class Department {
  • @OneToMany(mappedBy=”department”)
  • @MapKey(name=”name”)
  • public Map<String, Employee> getEmployees() {… }
  • }
    *
  • @Entity
  • public class Employee {
  • @Id public Integer getEmpId() { … }
  • @ManyToOne
  • @JoinColumn(name=”dept_id”)
  • public Department getDepartment() { … }
  • }

@MapKey 默认值为主键;

如果有name,指定的值为 持久化字段或者属性的值,这个name属性是可选的;

再看其属性:

name属性,同上解释,默认值为空字符串;

/**
 * (Optional) The name of the persistent field or property of the
 * associated entity that is used as the map key.
 * <p> Default: If the
 * <code>name</code> element is not specified, the primary key of the
 * associated entity is used as the map key. If the
 * primary key is a composite primary key and is mapped
 * as <code>IdClass</code>, an instance of the primary key
 * class is used as the key.
 */
String name() default "";

@MapKeyColumn

先看1个实例:

  • Example:
    *
  • @Entity
  • public class Item {
  • @Id int id;
  • @ElementCollection
  • @MapKeyColumn(name=”IMAGE_NAME”)
  • @Column(name=”IMAGE_FILENAME”)
  • @CollectionTable(name=”IMAGE_MAPPING”)
  • Map<String, String> images; // map from image name to filename
  • }

@MapKeyColumn 指向数据库字段,很实用的一个注解;

再看其属性:

name()

(Optional) The name of the map key column. The table in which it is found
* depends upon the context. If the map key is for an element collection,
* the map key column is in the collection table for the map value. If the
* map key is for a ManyToMany entity relationship or for a OneToMany entity
* relationship using a join table, the map key column is in a join table.
* If the map key is for a OneToMany entity relationship using a foreign key
* mapping strategy, the map key column is in the table of the entity that
* is the value of the map.
*

Defaults to the concatenation of the following: the name of
* the referencing relationship field or property; “_”; “KEY

这个字段很好的处理一对多或者多对多打的关系,如果作为外键,其值也会出现在对应的集合包含的对象里面;

boolean unique() default false;
唯一

boolean insertable() default true;
可插入

boolean updatable() default true;
可更新

String columnDefinition() default "";
列定义

String table() default "";
表

int length() default 255;
长度

int precision() default 0; // decimal precision
精确

int scale() default 0; // decimal scale
刻度

猜你喜欢

转载自blog.csdn.net/qq_37022150/article/details/77486311
今日推荐