RSS

OneToMany & ManyToOne Association

16 Mar

OneToMany & ManyToOne Bidirectional Association

Department MySQL

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

Employee MySQL

NAME TYPE NULLABLE KEY EXTRA
id int(11) NO PRI auto_increment
name varchar(20) NO    
age int(11) YES    
phone varchar(15) YES    
departmentid int(11) NO MUL  

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.Employee</class>

<class>com.xavier.ejb3.entitybean.Department</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>

 

Department.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

import java.util.Set;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.OneToMany;

import javax.persistence.Table;

import static javax.persistence.CascadeType.MERGE;

import static javax.persistence.CascadeType.REMOVE;

import static javax.persistence.CascadeType.REFRESH;

import static javax.persistence.FetchType.EAGER;

 

@SuppressWarnings(“serial”)

@Entity

@Table(name=“department”)

public class Department implements Serializable{

private int id;

private String name;

private Set<Employee> employees;

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(nullable=false)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@OneToMany (cascade = { MERGE, REMOVE, REFRESH }, fetch = EAGER, mappedBy = “department”)

public Set<Employee> getEmployees() {

return employees;

}

public void setEmployees(Set<Employee> employees) {

this.employees = employees;

}

}

 

Employee.java

package com.xavier.ejb3.entitybean;

import java.io.Serializable;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.ManyToOne;

import javax.persistence.Table;

import static javax.persistence.CascadeType.MERGE;

import static javax.persistence.CascadeType.REFRESH;

 

@SuppressWarnings(“serial”)

@Entity

@Table(name=“employee”)

public class Employee implements Serializable {

private int id;

private String name;

private int age;

private String phone;

private Department department;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(nullable=false)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Column(nullable=true)

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Column(nullable=true)

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

@ManyToOne(optional = false, cascade = { MERGE, REFRESH })

@JoinColumn(name=“departmentid”, referencedColumnName=“id”)

public Department getDepartment() {

return department;

}

public void setDepartment(Department department) {

this.department = department;

}

}

 

DepartmentLocal.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Department;

 

public interface DepartmentLocal {

public Department getDepartmentById(int id);

public void delDepartment(int id);

}

 

DepartmentBean.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Department;

import javax.ejb.Local;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

 

@Stateless

@Local(DepartmentLocal.class)

public class DepartmentBean implements DepartmentLocal {

@PersistenceContext(unitName=“ejb3”)

protected EntityManager em;

    public void delDepartment(int id) {

        em.remove(em.find(Department.class, id));

    }

 

    public Department getDepartmentById(int id) {

return em.find(Department.class, id);

    }

 

}

 

EmployeeLocal.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Employee;

 

public interface EmployeeLocal {

public void addEmployee(String name, int age, String phone, int departmentid);

public Employee getEmployeeById(int id);

public void deleteEmployee(int id);

}

 

EmployeeBean.java

package com.xavier.ejb3.sessionbean;

import com.xavier.ejb3.entitybean.Department;

import com.xavier.ejb3.entitybean.Employee;

import javax.ejb.Local;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

 

@Stateless

@Local(EmployeeLocal.class)

public class EmployeeBean implements EmployeeLocal {

@PersistenceContext(unitName=“ejb3”)

protected EntityManager em;

    public void addEmployee(String name, int age, String phone, int departmentid) {

        Employee employee = new Employee();

        Department department = new Department();

        department.setId(departmentid);

        employee.setDepartment(department);

        employee.setName(name);

        employee.setAge(age);

        employee.setPhone(phone);

        em.persist(employee);

    }

 

    public Employee getEmployeeById(int id) {

return em.find(Employee.class, id);

    }

   

    public void deleteEmployee(int id){

        Employee employee = em.find(Employee.class, id);

        em.remove(employee);

    }

}

 

OneToManyTest.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>One To Many</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”);

Context ctx = new InitialContext(jndiProperties);

EmployeeLocal el = (EmployeeLocal) ctx

.lookup(“ejb:ejb3/ejb3//EmployeeBean!com.xavier.ejb3.sessionbean.EmployeeLocal”);

//Add Employee

/*el.addEmployee(“Xavier”, 29, “13400000000”, 1);

el.addEmployee(“Nathaniel”, 28, “13100000000”, 1);

el.addEmployee(“Joe”, 27, “13500000000”, 1);

el.addEmployee(“Brian”, 30, “13800000000”, 1);

el.addEmployee(“Javier”, 26, “13900000000”, 1);*/

out.println(“<br>—————————-Successfully Added!”);

//Get Employee

Employee e = (Employee) el.getEmployeeById(1);

out.println(“<br>————–Print Employee info whose id is <1>——————“);

out.println(“<br>ID: “ + e.getId());

out.println(“<br>Name: “ + e.getName());

out.println(“<br>Age: “ + e.getAge());

out.println(“<br>Phone: “ + e.getPhone());

out.println(“<br>Department: “ + e.getDepartment().getName());

out.println(“<br>————–Successfully query”);

//Delete Employee

el.deleteEmployee(1);

out.println(“<br>———delete successfully!”);

 

} catch (Exception e) {

out.println(e.getMessage());

}

%>

</body>

</html>

Note: mappedBy is placed to the referenced table (which doesn’t have foreign key). @JoinColumn is placed in main table (which has foreign key).

 

OneToMany&ManyToOne Unidirectional Association

Remove Department.java @OneToMany annotation and Set<Employee> employees property.

Advertisements
 
Leave a comment

Posted by on 03/16/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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

 
%d bloggers like this: