这次说说OneToMany和ManyToOne
我们的场景是 1个父亲n多个孩子
先来看看这中做法:
TestFather.java
package net.paoding.forum.domain;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class TestFather
{
String id;
String name;
List<TestChild> children = new ArrayList<TestChild>();
/**
* @return the id
*/
@Id
public String getId()
{
return id;
}
/**
* @param id the id to set
*/
public void setId(String id)
{
this.id = id;
}
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return the children
*/
@OneToMany
public List<TestChild> getChildren()
{
return children;
}
/**
* @param children the children to set
*/
public void setChildren(List<TestChild> children)
{
this.children = children;
}
}
TestChild.java
package net.paoding.forum.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class TestChild
{
String id;
String name;
/**
* @return the id
*/
@Id
public String getId()
{
return id;
}
/**
* @param id the id to set
*/
public void setId(String id)
{
this.id = id;
}
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
}
这样子,好像就可以了。那么是的么?我们来看看hib产生的sql
drop table test_child cascade constraints;
drop table test_father cascade constraints;
drop table test_father_children cascade constraints;
create table test_child (
id varchar2(255 char) not null,
name varchar2(255 char),
primary key (id)
);
create table test_father (
id varchar2(255 char) not null,
name varchar2(255 char),
primary key (id)
);
create table test_father_children (
null_id varchar2(255 char) not null,
children_id varchar2(255 char) not null,
unique (children_id)
);
alter table test_father_children
add constraint FK2E6E87D5901B7DBB
foreign key (null_id)
references test_father;
alter table test_father_children
add constraint FK2E6E87D58CD0E56B
foreign key (children_id)
references test_child;
alter table test_user
add constraint FKB9A96B58A237D846
foreign key (card_id)
references test_card;
oh! My God !它居然又帮我们多创建了一个table。作为关联。太笨了。
很明显,这不是我们所需要的。
那我们该如何呢?