我不明白,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),
答案 0 :(得分:0)
Hibernate在第一种情况下创建了一个唯一的列,因为你正在使用@OneToMany
告诉hibernate一个类别最多只有一个父类。在您注释掉@JoinTable
的代码中,您还将@OneToMany
更改为@ManyToMany
。这就是hibernate在这种情况下不会创建唯一约束的原因。
我认为该类别的孩子将该类别本身作为父母。在这种情况下,必须使用mappedBy
中的@ManyToMany
将孩子或父母定义为关系的另一面:
@ManyToMany
@JoinTable(name = "category_childs")
private Set<Category> childs = new HashSet<Category>();
@ManyToMany(mappedBy="childs")
private Set<Category> parents = new HashSet<Category>();