在前面的例子中,我們演示了一對多和多對一的例子,在本章將演示多對多和一對一的關系。
學生和老師就是多對多的關系。一個學生有多個老師,一個老師教多個學生。
學生和檔案就是一對一的關系(不知道國外的學生有沒有檔案?)。
為了實現多對多的關系,數據庫中需要關聯表,用以在兩個實體間建立關聯。JBoss可以自動生成關聯表,你也可以@AssociationTable來指定關聯表的信息。
如:
@ManyToMany(cascade = {CascadeType.CREATE, CascadeType.MERGE}, fetch = FetchType.EAGER, isInverse = true)
@AssociationTable(table = @Table(name = "STUDENT_TEACHER"),
joinColumns = {@JoinColumn(name = "TEACHER_ID")},inverseJoinColumns = {@JoinColumn(name = "STUDENT_ID")})
@ AssociationTable的注釋聲明如下:
@Target({METHOD, FIELD})
public @interface AssociationTable {
Table table() default @Table(specified=false);
JoinColumn[] joinColumns() default {};
JoinColumn[] inverseJoinColumns() default {};
}
關聯表注釋指定了關聯表的名稱、主表的列和從表的列。
為了實現一對一的關系,需要用@OneToOne來注釋。
如:
@OneToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "DOSSIER_ID")
public Dossier getDossier()
{
return dossier;
}
這定義了一個單向的一對一的關系。如果在Dossier也定義了相關的關聯,那麼它就是雙向的。雙向的意思就是通過一個Student實體就可以查找到一個Dossier,通過一個Dossier就可以查找到一個Student。
@ OneToOne的注釋聲明如下:
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface OneToOne {
String targetEntity() default "";
CascadeType[] cascade() default {};
FetchType fetch() default EAGER;
boolean optional() default true;
}
這個例子主要有以下幾個文件,這個例子主要實現了學生和老師、學生和檔案之間的關系。Student、Teacher、Dossier都是實體Bean。Student和Dossier是一個雙向的OneToOne之間的關系,Student和Teacher是ManyToMany的關系,也是雙向的。和前面的例子一樣,我們還是使用Client測試。
Student.java:實體Bean。
Dossier.java:實體Bean所依賴的類。
Teacher.java:實體Bean所依賴的類。
EntityTest.java:會話Bean的業務接口
EntityTest Bean.java:會話Bean的實現類
Client.java:測試EJB的客戶端類。
jndi.properties:jndi屬性文件,提供訪問jdni的基本配置屬性。
Build.xml:ant 配置文件,用以編譯、發布、測試、清除EJB。
下面針對每個文件的內容做一個介紹。
Student.java
package com.kuaff.ejb3.relationships;
import javax.ejb.CascadeType;
import javax.ejb.Entity;
import javax.ejb.FetchType;
import javax.ejb.GeneratorType;
import javax.ejb.Id;
import javax.ejb.JoinColumn;
import javax.ejb.OneToOne;
import javax.ejb.ManyToMany;
import javax.ejb.Table;
import javax.ejb.AssociationTable;
import java.util.ArrayList;
import java.util.Set;
import java.util.Collection;
import java.io.Serializable;
@Entity
@Table(name = "STUDENT")
public class Student implements Serializable
{
private int id;
private String first;
private String last;
private Dossier dossier;
private Set<Teacher> teachers;
@Id(generate = GeneratorType.AUTO)
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public void setFirst(String first)
{
this.first = first;
}
public String getFirst()
{
return first;
}
public void setLast(String last)
{
this.last = last;
}
public String getLast()
{
return last;
}
public void setDossier(Dossier dossier)
{
this.dossier = dossier;
}
@OneToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "DOSSIER_ID")
public Dossier getDossier()
{
return dossier;
}
public void setTeacher(Set<Teacher> teachers)
{
this.teachers = teachers;
}
@ManyToMany(cascade = {CascadeType.CREATE, CascadeType.MERGE}, fetch = FetchType.EAGER, isInverse = true)
@AssociationTable(table = @Table(name = "STUDENT_TEACHER"),
joinColumns = {@JoinColumn(name = "TEACHER_ID")},inverseJoinColumns = {@JoinColumn(name = "STUDENT_ID")})
public Set<Teacher> getTeacher()
{
return teachers;
}
}
Dossier.java
package com.kuaff.ejb3.relationships;
import javax.ejb.Entity;
import javax.ejb.GeneratorType;
import javax.ejb.Id;
@Entity
public class Dossier implements java.io.Serializable
{
private Long id;
private String resume;
@Id(generate = GeneratorType.AUTO)
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public void setResume(String resume)
{
this.resume = resume;
}
public String getResume()
{
return resume;
}
}
Teacher.java
package com.kuaff.ejb3.relationships;
import javax.ejb.AssociationTable;
import javax.ejb.Basic;
import javax.ejb.CascadeType;
import javax.ejb.Column;
import javax.ejb.Entity;
import javax.ejb.FetchType;
import javax.ejb.Id;
import javax.ejb.JoinColumn;
import javax.ejb.ManyToMany;
import javax.ejb.Table;
import javax.ejb.Transient;
import javax.ejb.Version;
import java.util.Set;
import javax.ejb.GeneratorType;
@Entity
public class Teacher implements java.io.Serializable
{
private Long id;
private String resume;
private String name;
private String info;
private Set<Student> students;
@Id(generate = GeneratorType.IDENTITY)
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setInfo(String info)
{
this.info = info;
}
public String getInfo()
{
return info;
}
public void setStudents(Set<Student> students)
{
this.students = students;
}
@ManyToMany(cascade = {CascadeType.CREATE, CascadeType.MERGE}, fetch = FetchType.EAGER)
@AssociationTable(table = @Table(name = "STUDENT_TEACHER"),
joinColumns = {@JoinColumn(name = "TEACHER_ID",referencedColumnName="ID")},
inverseJoinColumns = {@JoinColumn(name = "STUDENT_ID",referencedColumnName="ID")})
public Set<Student> getStudents()
{
return students;
}
}
EntityTest.java
package com.kuaff.ejb3.relationships;
import javax.ejb.Remote;
import java.util.List;
@Remote
public interface EntityTest
{
public void createData();
public List findByName(String name);
}
EntityTestBean.java
package com.kuaff.ejb3.relationships;
import javax.ejb.EntityManager;
import javax.ejb.Inject;
import javax.ejb.Stateless;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
@Stateless
public class EntityTestBean implements EntityTest
{
private @Inject EntityManager manager;
public void createData()
{
Teacher teacher1 = new Teacher();
Teacher teacher2 = new Teacher();
Set<Student> students1 = new HashSet<Student>();
Set<Student> students2 = new HashSet<Student>();
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Dossier dossier1 = new Dossier();
Dossier dossier2 = new Dossier();
Dossier dossier3 = new Dossier();
teacher1.setId(new Long(1));
teacher1.setName("hushisheng");
teacher1.setInfo("胡時勝教授,博士生導師");
manager.create(teacher1);
teacher2.setId(new Long(2));
teacher2.setName("liyongchi");
teacher2.setInfo("李永池教授,博士生導師");
manager.create(teacher2);
student1.setFirst("晁");
student1.setLast("岳攀");
dossier1.setResume("這是晁岳攀的檔案");
student1.setDossier(dossier1);
students1.add(student1);
student2.setFirst("趙");
student2.setLast("志偉");
dossier2.setResume("這是趙志偉的檔案");
student2.setDossier(dossier2);
students1.add(student2);
student3.setFirst("田");
student3.setLast("明");
dossier3.setResume("這是田明的檔案");
student3.setDossier(dossier3);
students2.add(student3);
teacher1.setStudents(students1);
teacher2.setStudents(students2);
}
public List findByName(String name)
{
return manager.createQuery("from Teacher t where t.name = :name").setParameter("name", name).listResults();
}
}
在這個會話Bean中提供了創建各個實體Bean的方法,並提供了查找老師的方法。
Client.java
package com.kuaff.ejb3.secondary;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.List;
public class Client
{
public static void main(String[] args) throws NamingException
{
InitialContext ctx = new InitialContext();
StudentDAO dao = (StudentDAO) ctx.lookup(StudentDAO.class.getName());
int id = dao.create("晁","岳攀","8","[email protected]","男");
dao.create("朱","立煥","6","[email protected]","女");
List list = dao.findAll();
for(Object o:list)
{
Student s = (Student)o;
System.out.printf("%s%s的性別:%s%n",s.getName().getFirst(),s.getName().getLast(),s.getGender());
dao.evict(s);
}
}
}
這個客戶端用來測試。
請運行{$JBOSS_HOME}/bin目錄下的run.bat: run –c all,啟動JBOSS。
http://localhost:8080/jmx-console/HtmlAdaptor?action=inspectMBean&name=jboss%3Aservice%3DHypersonic%2Cdatabase%3DlocalDB,然後調用startDatabaseManager()方法,打開HSQL管理工具管理數據庫。
在Eclipse的Ant視圖中執行ejbjar target。或者在命令行下,進入到此工程目錄下,執行ant ejbjar,將編譯打包發布此EJB。
在Eclipse的Ant視圖中執行run target。或者在命令行下,進入到此工程目錄下,執行ant run,測試這個EJB。