Thursday, July 26, 2012

7. Many-To-Many Relation Mapping


පහත දැක්වෙන්නේ Many-To-Many relationship එකක් map කරන ආකාරය.


Meeting සහ Employee classes දෙක අතර සම්බන්ධය Many-To-Many ලෙස ගනිමු.

එනම් එක Meeting එකක Employees ලා බොහෝ සිටිය හැක.
එක Employee කෙනෙක් බොහෝ Meeting ගණනකට සහභාගි විය හැක.


a)  package abc.hibernate;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.ManyToMany;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.CascadeType;





@Entity
@Table(name="employee")
public class Employee{

@Id
@GeneratedValue
@Column(name="emp_id")
private Long empId;

@Column(name="first_name")
private String firstName;

@Column(name="last_name")
private String lastName;

@Column(name="birth_date")
private Date birth_date;

@Column(name="salary")
private double salary;

@ManyToMany(cascade={CascadeType.ALL })
@JoinTable(name="employee_meeting",
                       joinColumns={@JoinColumn(name="emp_id")},
                       inverseJoinColumns={@JoinColumn(name="meeting_id")})
private Set<Meeting> meetings = new HashSet<Meeting>(); 

public Employee(){
}

public Employee(String firstname, String lastname, Date birthdate, double salary){
this.firstName = firstname;
this.lastName = lastname ;
this.birthDate = birthdate ;
this.salary = salary ;
}

//Getter and Setter methods

}




---------------------------------------------------------------------------------------------




b)   package abc.hibernate;


import java.util.Date;
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.Table;
import javax.persistence.ManyToMany;


@Entity
@Table(name="meeting")
public class Meeting {


@Id
@Column(name="meeting_id")
@GeneratedValue
private Long meetingId ;


@Column(name="subject")
private String Subject;


@Column(name="meeting_date")
private Date meetingDate;


@ManyToMany(mappedBy="meetings")
private Set<Employee> employees = new HashSet<Employee>();


private Meeting(String subject){
this.subject= subject;
this.meeting_date = new Date();
}


//Getters and Setters


}







No comments:

Post a Comment