0

我不明白,Hibernate 是否应该自动工作?

我有Category编码如下的实体:

@Entity
public class Category {

@Id
public String Url;

@OneToMany
@JoinTable(name = "category_childs")
private Set<Category> childs = new HashSet<Category>();

@OneToMany
@JoinTable(name = "category_parents")
private Set<Category> parents = new HashSet<Category>();

@OneToMany(cascade=CascadeType.ALL)
private Set<Person> persons = new HashSet<Person>();

public String Title;

public boolean Done;

这会导致创建下表

CREATE TABLE
category_parents
(
    Category_Url VARCHAR(255) NOT NULL,
    parents_Url VARCHAR(255) NOT NULL,
    PRIMARY KEY (Category_Url, parents_Url),
    CONSTRAINT FK9BB292C83275D6D7 FOREIGN KEY (Category_Url) REFERENCES category (Url) ,
    CONSTRAINT FK9BB292C8569C2962 FOREIGN KEY (parents_Url) REFERENCES category (Url),
    CONSTRAINT parents_Url UNIQUE (parents_Url),

这是不正确的,因为parents_Url不应该是唯一的(应该允许多行具有相同的父级)。

如果我在没有@JoinTable 规范的情况下编码

@Entity
public class Category {

@Id
public String Url;

@ManyToMany(cascade=CascadeType.ALL)
//@JoinTable(name = "category_childs")
private Set<Category> childs = new HashSet<Category>();

@ManyToMany(cascade=CascadeType.ALL)
//@JoinTable(name = "category_parents")
private Set<Category> parents = new HashSet<Category>();

@OneToMany(cascade=CascadeType.ALL)
private Set<Person> persons = new HashSet<Person>();

public String Title;

public boolean Done;

那么我将有以下

CREATE TABLE
category_category
(
    Category_Url VARCHAR(255) NOT NULL,
    parents_Url VARCHAR(255) NOT NULL,
    childs_Url VARCHAR(255) NOT NULL,
    PRIMARY KEY (Category_Url, childs_Url),
    CONSTRAINT FK8635931F3275D6D7 FOREIGN KEY (Category_Url) REFERENCES category (Url) ,
    CONSTRAINT FK8635931F569C2962 FOREIGN KEY (parents_Url) REFERENCES category (Url) ,
    CONSTRAINT FK8635931F6ADF3430 FOREIGN KEY (childs_Url) REFERENCES category (Url),

如何让 Hibernate 创建具有两个字段的关系表?

如下:

CREATE TABLE
category_category
(
    parents_Url VARCHAR(255) NOT NULL,
    childs_Url VARCHAR(255) NOT NULL,
    PRIMARY KEY (parents_Url, childs_Url),
    CONSTRAINT FK8635931F569C2962 FOREIGN KEY (parents_Url) REFERENCES category (Url) ,
    CONSTRAINT FK8635931F6ADF3430 FOREIGN KEY (childs_Url) REFERENCES category (Url),
4

1 回答 1

0

Hibernate 在第一种情况下创建了一个唯一列,因为您正在使用@OneToMany它告诉 hibernate 一个类别最多有一个父级。在您注释掉的代码中,@JoinTable您也更改@OneToMany@ManyToMany. 这就是为什么 hibernate 在这种情况下不会创建唯一约束的原因。

我想该类别的孩子将类别本身作为父母。mappedBy在这种情况下,必须使用in将孩子或父母定义为关系的另一方@ManyToMany

@ManyToMany
@JoinTable(name = "category_childs")
private Set<Category> childs = new HashSet<Category>();

@ManyToMany(mappedBy="childs")
private Set<Category> parents = new HashSet<Category>();
于 2012-09-17T18:19:19.883 回答