我不明白,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),