Hibernates - Many to One Association
May 12, 2011 What is Association? Association is the relation between two objects. One class holds a reference of other object. This relation is similar to '”has-a” relation. Based on the cardinality of the relationship, the following categories exist. - One-to-one. - One-to-many. - Many-to-one. - Many-to-many.
May 12, 2011 Many-to-One Association Most common kind of association. An object is associated with multiple objects. For example, a person can own more than one car. Relation between an employee and address. Has A EMPLOYEE ADDRESS N 1
May 12, 2011 Example: Association Between Employees and Address 1.RDBMS Tables: EMPLOYEE Table create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, address INT NOT NULL, PRIMARY KEY (id) ); ADDRESS Table create table ADDRESS ( id INT NOT NULL auto_increment, street_name VARCHAR(40) default NULL, city_name VARCHAR(40) default NULL, state_name VARCHAR(40) default NULL, zipcode VARCHAR(10) default NULL, PRIMARY KEY (id) );
May 12, POJO Classes public class Employee { private int id; private String firstName; private String lastName; private int salary; private Address address; //getters and setters } public class Address { private int id; private String street; private String city; private String state; private String zipcode; //getters and setters }
May 12, POJO Classes public class Employee { private int id; private String firstName; private String lastName; private int salary; private Address address; //getters and setters } public class Address { private int id; private String street; private String city; private String state; private String zipcode; //getters and setters }
May 12, Mapping Files Employee.hbm.xml This class contains the employee detail. <many-to-one name="address" column="address" class="Address" not-null="true"/>
May 12, 2011 Address.hbm.xml This class contains the address detail.
May 12, 2011 First Name: Manoj Last Name: Kumar Salary: 4000 Address Street: Kondapur City: Hyderabad State: AP Zipcode: 532 select * from EMPLOYEE; id first_name last_name salary address Manoj Kumar select * from ADDRESS; id street_name city_name state_name zipcode Kondapur Hyderabad AP
Thank You