RSS

ManyToMany Association

17 Mar

ManyToMany Bidirectional Association

Teacher

NAME TYPE NULLABLE KEY EXTRA
tid int(11) NO PRI auto_increment
name varchar(20) NO    
techType varchar(20) YES    

Student

NAME TYPE NULLABLE KEY EXTRA
sid int(11) NO PRI auto_increment
name varchar(20) NO    

Teacher_Student

NAME TYPE NULLABLE KEY EXTRA
teacher_id int(11) NO PRI  
student_id int(11) NO PRI  

persistence.xml

<?xml version=“1.0” encoding=“UTF-8”?>

<persistence version=“2.0”

xmlns=http://java.sun.com/xml/ns/persistence&#8221; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221;

xsi:schemaLocation=http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd>

<persistence-unit name=“ejb3” transaction-type=“JTA”>

<provider>org.hibernate.ejb.HibernatePersistence</provider>

<jta-data-source>java:/DefaultMySqlDS</jta-data-source>

<class>com.xavier.ejb3.entitybean.Teacher</class>

<class>com.xavier.ejb3.entitybean.Student</class>

<properties>

<property name=“hibernate.show_sql” value=“true” />

<property name=“hibernate.format_sql” value=“true” />

<property name=“hibernate.dialect” value=“org.hibernate.dialect.MySQLDialect” />

</properties>

</persistence-unit>

</persistence>

 

Teacher.java

package com.xavier.ejb3.entitybean;

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.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.ManyToMany;

import javax.persistence.Table;

import static javax.persistence.GenerationType.IDENTITY;

import static javax.persistence.FetchType.EAGER;

import javax.persistence.JoinTable;

import javax.persistence.JoinColumn;

 

@SuppressWarnings(“serial”)

@Entity

@Table(name = “teacher”)

public class Teacher implements Serializable {

private int tid;

private String name;

private String techType;

private Set<Student> students = new HashSet<Student>();

public Teacher(){

}

public Teacher(String name, String techType){

this.name = name;

this.techType = techType;

this.students = null;

}

 

@Id

@GeneratedValue(strategy = IDENTITY)

public int getTid() {

return tid;

}

 

public void setTid(int tid) {

this.tid = tid;

}

 

@Column(nullable = false)

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

@Column(nullable = false)

public String getTechType() {

return techType;

}

 

public void setTechType(String techType) {

this.techType = techType;

}

 

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = EAGER)

@JoinTable(name = “teacher_student”,

joinColumns = @JoinColumn(name = “teacher_id”, referencedColumnName = “tid”), 

inverseJoinColumns = @JoinColumn(name = “student_id”, referencedColumnName = “sid”))

public Set<Student> getStudents() {

return students;

}

 

public void setStudents(Set<Student> students) {

this.students = students;

}

 

}

 

Student.java

package com.xavier.ejb3.entitybean;

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;

import static javax.persistence.GenerationType.IDENTITY;

import static javax.persistence.CascadeType.ALL;

import static javax.persistence.FetchType.EAGER;

 

@SuppressWarnings(“serial”)

@Entity

@Table(name=“student”)

public class Student implements Serializable {

private int sid;

private String name;

private Set<Teacher> teachers = new HashSet<Teacher>();

public Student(){

}

public Student(String name){

this.name = name;

this.teachers = null;

}

@Id

@GeneratedValue(strategy = IDENTITY)

public int getSid() {

return sid;

}

public void setSid(int sid) {

this.sid = sid;

}

@Column(nullable=false)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@ManyToMany(cascade = ALL, fetch = EAGER, mappedBy = “students”)

public Set<Teacher> getTeachers() {

return teachers;

}

public void setTeachers(Set<Teacher> teachers) {

this.teachers = teachers;

}

}

 

TeacherStudentLocal.java

package com.xavier.ejb3.sessionbean;

import java.util.Set;

import com.xavier.ejb3.entitybean.Student;

import com.xavier.ejb3.entitybean.Teacher;

 

public interface TeacherStudentLocal {

public void addTeacher(String name,String techType, Set<Student> students);

public Teacher getTeacherById(int tid);   

public void removeTeacher(int tid);

public void removeTeacherKeepStudent(int tid);

public void removeMiddleTable(int tid);

}

 

TeacherStudentBean.java

package com.xavier.ejb3.sessionbean;

import java.util.Set;

import com.xavier.ejb3.entitybean.Student;

import com.xavier.ejb3.entitybean.Teacher;

import javax.ejb.Local;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

import javax.persistence.Query;

 

@Stateless

@Local(TeacherStudentLocal.class)

public class TeacherStudentBean implements TeacherStudentLocal {

 

@PersistenceContext(name=“ejb3”)

protected EntityManager em;

    public void addTeacher(String name, String techType, Set<Student> students) {

       Teacher teacher = new Teacher(name, techType);

       teacher.setStudents(students);

       em.persist(teacher);

    }

 

    public Teacher getTeacherById(int tid) {

return em.find(Teacher.class, tid);

    }

 

    public void removeTeacher(int tid){

        em.remove(em.find(Teacher.class, tid));

    }

   

    public void removeTeacherKeepStudent(int tid){

        Teacher teacher = em.find(Teacher.class, tid);

        Set<Student> students = teacher.getStudents();

        for(Student student : students){

            student.setTeachers(null);

        }

        em.remove(teacher);

    }

   

    public void removeMiddleTable(int tid){

        Query query = em.createNativeQuery(“delete from teacher_student where teacher_id = :tid”);

        query.setParameter(“tid”, tid);

        query.executeUpdate();

    }

}

 

ManyToManyTest.jsp

<%@ page language=“java” contentType=“text/html; charset=UTF-8”

pageEncoding=“UTF-8”%>

<%@ page

import=“javax.naming.*,com.xavier.ejb3.sessionbean.*,com.xavier.ejb3.entitybean.*,java.util.*”%>

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” http://www.w3.org/TR/html4/loose.dtd>

<html>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8”>

<title>Many To Many Test</title>

</head>

<body>

<%

try {

final Hashtable jndiProperties = new Hashtable();

jndiProperties.put(Context.PROVIDER_URL, “localhost:1099”);

jndiProperties.put(Context.URL_PKG_PREFIXES,

“org.jboss.ejb.client.naming”);

//jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, “org.jnp.interfaces.NamingContextFactory”);

//org.jboss.naming.remote.client.InitialContextFactory

Context ctx = new InitialContext(jndiProperties);

TeacherStudentLocal tsl = (TeacherStudentLocal) ctx

.lookup(“ejb:ejb3/ejb3//TeacherStudentBean!com.xavier.ejb3.sessionbean.TeacherStudentLocal”);

//Add Teacher

/*Set<Student> students = new HashSet<Student> ();

students.add(new Student(“Xavier”));

students.add(new Student(“Joe”));

students.add(new Student(“Javier”));

tsl.addTeacher(“Zoe”, “Math”, students);*/

//Get Teacher

/*Teacher t = tsl.getTeacherById(3);

out.println(“<br>———————Teacher Information————————-“);

out.println(“<br>Teacher Name: ” + t.getName());

out.println(“<br>Teaches: ” + t.getTechType());

out.println(“<br>All his/her students: “);

students.clear();

students = t.getStudents();

for(Student s: students){

out.println(s.getName() + “\t”);

}*/

 

//Delete Teacher and remove all her students.

//tsl.removeTeacher(4);

//tsl.removeTeacherKeepStudent(4);

tsl.removeMiddleTable(1);

 

} catch (Exception e) {

out.println(e.getMessage());

}

%>

</body>

</html>

 

ManyToMany Unidirectional Association

Remove Student.java @ManyToMany annotation and Set<Teacher> teachers property.

Advertisements
 
Leave a comment

Posted by on 03/17/2012 in EJB

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: