文档章节

EJB---->多对多映射

小强斋太
 小强斋太
发布于 2016/11/09 20:07
字数 757
阅读 0
收藏 0

多对多映射

学生和老师就是多对多的关系。一个学生有多个老师,一个老师教多个学生。多对多映射采取中间表连接的映射策略,建立的中间表将分别引入两边的主键作为外键。EJB3 对于中间表的元数据提供了可配置的方式,用户可以自定义中间表的表名,列名。

需要映射的数据表:

Student.java

package com.foshanshop.ejb3.bean;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@SuppressWarnings("serial")
@Entity
@Table(name = "Student")
public class Student implements Serializable{
private Integer studentid;
private String StudentName;
private Set<Teacher> teachers = new HashSet<Teacher>();
public Student() {}
public Student(String studentName) {
StudentName = studentName;
}
@Id
@GeneratedValue
public Integer getStudentid() {
return studentid;
}
public void setStudentid(Integer studentid) {
this.studentid = studentid;
}
@Column(nullable=false, length=32)
public String getStudentName() {
return StudentName;
}
public void setStudentName(String studentName) {
StudentName = studentName;
}
@ManyToMany(mappedBy = "students")
public Set<Teacher> getTeachers() {
return teachers;
}
public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}
}

@ManyToMany 注释表示Student 是多对多关系的一边,mappedBy 属性定义了Student 为双向关系的维护端(owning side)。
Teacher.java

package com.foshanshop.ejb3.bean;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@SuppressWarnings("serial")
@Entity
@Table(name = "Teacher")
public class Teacher implements Serializable{
private Integer teacherid;
private String TeacherName;
private Set<Student> students = new HashSet<Student>();
public Teacher() {}
public Teacher(String teacherName) {
TeacherName = teacherName;
}
@Id
@GeneratedValue
public Integer getTeacherid() {
return teacherid;
}
public void setTeacherid(Integer teacherid) {
this.teacherid = teacherid;
}
@Column(nullable=false, length=32)
public String getTeacherName() {
return TeacherName;
}
public void setTeacherName(String teacherName) {
TeacherName = teacherName;
}
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinTable(name = "Teacher_Student",
joinColumns = {@JoinColumn(name = "Teacher_ID", referencedColumnName = "teacherid")},
inverseJoinColumns = {@JoinColumn(name = "Student_ID", referencedColumnName =
"studentid")})
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
public void addStudent(Student student) {
if (!this.students.contains(student)) {
this.students.add(student);
}
}
public void removeStudent(Student student) {
this.students.remove(student);
}
}

@ManyToMany 注释表示Teacher 是多对多关系的一端。@JoinTable 描述了多对多关系的数据表关系。name 属性指定中间表名称,joinColumns 定义中间表与Teacher 表的外键关系。上面的代码中,中间表Teacher_Student的Teacher_ID 列是Teacher 表的主键列对应的外键列,inverseJoinColumns 属性定义了中间表与另外一端(Student)
的外键关系。

TeacherDAOBean.java

package com.foshanshop.ejb3.impl;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.foshanshop.ejb3.TeacherDAO;
import com.foshanshop.ejb3.bean.Student;
import com.foshanshop.ejb3.bean.Teacher;
@Stateless
@Remote ({TeacherDAO.class})
public class TeacherDAOBean implements TeacherDAO {
@PersistenceContext
protected EntityManager em;
public void insertTeacher(String name, String[] studentnames) {
Teacher teacher = new Teacher(name);
if (studentnames!=null){
for(int i=0;i<studentnames.length; i++){
teacher.addStudent(new Student(studentnames[i]));
}
}
em.persist(teacher);
}
public Teacher getTeacherByID(Integer teacherid) {
Teacher teacher= em.find(Teacher.class, teacherid);
if (teacher!=null) teacher.getStudents().size();
return teacher;
}
public Student getStudentByID(Integer studentid) {
Student student= em.find(Student.class, studentid);
if (student!=null) student.getTeachers().size();
return student;
}
}

ManyToManyTest.jsp

import="com.foshanshop.ejb3.TeacherDAO,
com.foshanshop.ejb3.bean.*,
javax.naming.*,
java.util.*"%>
<%
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
"org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.provider.url", "localhost:1099");
props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
InitialContext ctx = new InitialContext(props);
try {
TeacherDAO teacherdao = (TeacherDAO) ctx.lookup("TeacherDAOBean/remote");
teacherdao.insertTeacher("李老师",new String[]{"张小红","朱小光","龚利"});
Teacher teacher = teacherdao.getTeacherByID(new Integer(1));
if (teacher!=null){
out.println("======= 获取编号为1的老师姓名:"+ teacher.getTeacherName() +"
======<br>");
Iterator iterator = teacher.getStudents().iterator();
while (iterator.hasNext()){
Student student = (Student) iterator.next();
out.println("  他的学生:"+ student.getStudentName() +"<br>");
}
}else{
out.println("没有找到编号为1的老师<br>");
}
Student student = teacherdao.getStudentByID(new Integer(1));
if (student!=null){
out.println("======= 获取编号为1的学生姓名:"+ student.getStudentName() +"
======<br>");
Iterator iterator = student.getTeachers().iterator();
while (iterator.hasNext()){
Teacher tc = (Teacher) iterator.next();
out.println("  他的老师:"+ tc.getTeacherName() +"<br>");
}
}else{
out.println("没有找到编号为1的学生<br>");
}
} catch (Exception e) {
out.println(e.getMessage());
}
%>




 

 

本文转载自:http://www.cnblogs.com/xqzt/archive/2012/05/18/5637322.html

共有 人打赏支持
小强斋太
粉丝 0
博文 181
码字总数 0
作品 0
广州
Spring Data JPA实战视频教程

Spring Data JPA实战视频教程 视频大纲 JPA入门 Spring Data JPA入门 Repository的定义 查询方法的命名策略 JPQL查询,结果映射 Named Query,Named Native Query 排序,分页 JPA Criteria查...

刘宗泽
06/26
0
0
Servlet的一些细节--学习笔记

Servlet细节 1)浏览器访问的url-pattern只是一个符合格式的任意字符串,以/开头 2)一个Servlet的url-pattern可以是1个或多个,有二种形式; a).xx b)/xx/ 注意:/不能一起直接使用 3)/和....

知止内明
04/17
0
0
由浅入深,解析Java Servlet工作过程

Servlet简介 Servlet是sun公司提供的一门用于开发动态web资源的技术。 Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向浏览器输出数据),需要完成...

在北方玩弹子球
07/13
0
0
深入理解Spring MVC 思想

一、前言 二、spring mvc 核心类与接口 三、spring mvc 核心流程图 四、spring mvc DispatcherServlet说明 五、spring mvc 父子上下文的说明 六、springMVC-mvc.xml 配置文件片段讲解 七、s...

qq58edf1d989a2d
06/26
0
0
Spring中HttpInvoker远程调用使用实例

代码结构图如下: 客户端通过Spring的HttpInvoker,完成对远程函数的调用。涉及的类有: 客户端调用User类的服务UserService,完成对实现类UserServiceImpl的addUser(User u)方法调用。其中...

方绍伟
2013/10/09
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Spark Load Data and Export Data

Load_Data_Command 一、导入数据-加载csv文件数据作为spark 临时表DataSource(不需要提前创建表,方便数据分析) 该命令将csv文件导入到临时表中,命令格式为 load data '文件路径' table [...

Avner
8分钟前
0
0
CDH5.13离线安装Spark2.3详细步骤

简介: 在我的CDH5.13集群中,默认安装的spark是1.6版本,这里需要将其升级为spark2.x版本。经查阅官方文档,发现spark1.6和2.x是可以并行安装的,也就是说可以不用删除默认的1.6版本,可以直...

hblt-j
11分钟前
0
0
Add XSS protection headers on Nginx

Add XSS protection headers on Nginx Add the following line in the http or server part of your Nginx configuration : ... # XSS Protection add_header X-Frame-Opt......

idoz
12分钟前
0
0
cmake windows 配置xp toolset

MPRO
18分钟前
0
0
day125-20181023-英语流利阅读-待学习

外卖员不要哭,打零工不容易 雪梨 2018-10-23 1.今日导读 上期我们讲到,有人认为:“零工经济”虽然没有占领全世界,但它剥夺了劳动者的合法权利,加剧了工作的不稳定性,那么“零工经济”是...

飞鱼说编程
30分钟前
9
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部