Saturday, December 31, 2011

One table for 2 or More Classes

In some situations we may need create 1 table out of 2 or more classes. for instance when we map inheritance.

New Annotations :
  • @Embeddable : when a class is going to be embedded inside another persistence class we have to annotate the class as embeddable
  • @Embedded : When some (object) field is going to persist inside a class. The object type must annotated as embeddable

School.java

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class School {
 private int schoolId;
 private String schoolName;
 
 private SchoolDetails schoolDetails;
 
 @Id
 @GeneratedValue
 public int getSchoolId() {
  return schoolId;
 }
 public void setSchoolId(int schoolId) {
  this.schoolId = schoolId;
 }
 public String getSchoolName() {
  return schoolName;
 }
 public void setSchoolName(String schoolName) {
  this.schoolName = schoolName;
 }
 
 @Embedded
 public SchoolDetails getSchoolDetails() {
  return schoolDetails;
 }
 public void setSchoolDetails(SchoolDetails schoolDetails) {
  this.schoolDetails = schoolDetails;
 }
}

SchoolDetails.java
import javax.persistence.Embeddable;

@Embeddable
public class SchoolDetails {
 private String schoolAddress;
 private boolean isPrivateSchool;
 private int studentCount;
 
 
 public String getSchoolAddress() {
  return schoolAddress;
 }
 public void setSchoolAddress(String schoolAddress) {
  this.schoolAddress = schoolAddress;
 }
 public boolean isPrivateSchool() {
  return isPrivateSchool;
 }
 public void setPrivateSchool(boolean isPrivateSchool) {
  this.isPrivateSchool = isPrivateSchool;
 }
 public int getStudentCount() {
  return studentCount;
 }
 public void setStudentCount(int studentCount) {
  this.studentCount = studentCount;
 } 
}

Test.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  AnnotationConfiguration config=new AnnotationConfiguration();
  config.addAnnotatedClass(School.class);
  config.configure("hibernate.cfg.xml");
  
  new SchemaExport(config).create(true, true);
  
  SessionFactory factory=config.buildSessionFactory();
  Session session=factory.getCurrentSession();
  
  session.beginTransaction();
  
  SchoolDetails schDtl=new SchoolDetails();
  schDtl.setPrivateSchool(false);
  schDtl.setSchoolAddress("Richmond College,Richmond Hill,Galle");
  schDtl.setStudentCount(3000);
  
  School richmond=new School();
  richmond.setSchoolDetails(schDtl);
  richmond.setSchoolName("richmond College Galle");
  
  session.saveOrUpdate(richmond);
  session.getTransaction().commit();
 }
}

Result :


0 comments:

Post a Comment

© kani.stack.notez 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis