这个 Hibernate 实体 class 究竟是如何工作的?如何正确定义另一个实体表示的字段class?

How exactly works this Hibernate entity class? How to correctly define a field representd by another entity class?

我是 Hibernate 的新手,我有以下疑问。

我有这个实体 class:

@Entity
@Table(name = "KM_COUNTRY_AREA")
public class KMCountryArea implements Serializable {

    @Id
    @GeneratedValue
    private Long idCountryArea;

    @Column(name = "nomeFolder")
    private String nomeFolder;

    @Column(name = "country")
    private KMCountry country;

    // GETTER & SETTER METHODS

}

我对这个字段定义有疑问:

@Column(name = "country")
private KMCountry country;

其中 KMCountry 是另一个实体 class。那么它到底是什么意思呢?我认为 Hibernate 自动使用 KMCountry class.

的 table mappend 的 id

它是正确的还是我遗漏了什么?

EDIT-1:

所以我改变了:

@Column(name = "country")
private KMCountry country;

至:

@OneToOne(mappedBy = "country", cascade = CascadeType.ALL)
private KMCountry country;

其中 country 是将包含 KMCountry id 到我的数据库上的 KM_COUNTRY_AREA table 中的字段的名称。正确吗?

或者正确的语法是:

@OneToOne
private KMCountry country;

因为我必须使用 KMCountry 国家/地区 对象的主键?

cascade = CascadeType.ALL属性是什么意思?

Tnx

不能使用@Column注解来定义,必须使用Mapping entity associations/relationships.

根据您的情况,我认为您可以使用 一对一映射

看看这个教程:

编辑:

回答您编辑中的问题:

  1. 字段定义:

使用以下代码定义您的字段:

@OneToOne(mappedBy = "countryArea", cascade = CascadeType.ALL)
private KMCountry country;

其中 countryArea 指的是您必须在 KMcountry class 中添加的字段,如下所示:

@OneToOne  
@PrimaryKeyJoinColumn  
private KMCountryArea countryArea; 

并且在您的数据库中,您只会在 KM_Country table.[=19= 中引用 KMCountryArea id ]

  1. cascade = CascadeType.ALL的含义:

Cascading is about keeping dependency between two entities, for example deletion of one object from the database causing deletion of other dependent objects and CascadeType.ALL means that all the changes at parent class object will effect child class object too

JPA 级联类型:

Java持久化架构支持的级联类型如下:

  • CascadeType.PERSIST : 表示 save() 或 persist() 操作级联到相关实体。
  • CascadeType.MERGE : 表示合并拥有实体时,相关实体合并到托管状态。
  • CascadeType.REFRESH : 对 refresh() 操作做同样的事情。
  • CascadeType.REMOVE : 删除拥有实体时删除与此设置关联的所有相关实体。
  • CascadeType.DETACH : 如果发生“手动分离”,则分离所有相关实体。
  • CascadeType.ALL : 对于上述所有级联操作都是 shorthand。

查看 Hibernate Annotations-Cascade and Hibernate JPA Cascade Types 了解更多信息。