eclipse + JBoss 5 + EJB3开发指南(7)
时间:2011-09-18 blogjava 哈佛校训
实现Entity Bean的一对一(one-to-one)映射
一对一映射是很常用的。在一般情况下,一个主表通过外键和从表形成一对一的关系。在EJB3中使用 @OneToOne注释来映射。一对一关系除了使用外键进行关联外,也可以采用共享主键的方式连接两个表。 先看看如下两个表的结构:
图1 t_customers
图2 t_referees
t_customers和t_referees表形成了一对一的关系。t_customers表通过referee_id与t_referees表相 连。与t_customers表对应的实体Bean的代码如下:
package entity;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "t_customers")
public class Customer
{
private int id;
private String name;
private Referee referee;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@OneToOne
public Referee getReferee()
{
return referee;
}
public void setReferee(Referee referee)
{
this.referee = referee;
}
}
eclipse + JBoss 5 + EJB3开发指南(7)(2)
时间:2011-09-18 blogjava 哈佛校训
从上面的代码可以看出,getReferee方法使用了@OneToOne进行设置。在装载Customer对象的同时, Referee对象会被同时装载,而默认的外键字段就是Customer类中的referee属性名 + "_" + id,也就是 referee_id。下面看一下与t_referees表对应的实体Bean代码:
package entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="t_referees")
public class Referee
{
private int id;
private String name;
private Customer customer;
@OneToOne(mappedBy="referee")
public Customer getCustomer()
{
return customer;
}
public void setCustomer(Customer customer)
{
this.customer = customer;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
eclipse + JBoss 5 + E |