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

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

public class School {
 private int schoolId;
 private String schoolName;
 private SchoolDetails schoolDetails;
 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;
 public SchoolDetails getSchoolDetails() {
  return schoolDetails;
 public void setSchoolDetails(SchoolDetails schoolDetails) {
  this.schoolDetails = schoolDetails;
import javax.persistence.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;
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();
  new SchemaExport(config).create(true, true);
  SessionFactory factory=config.buildSessionFactory();
  Session session=factory.getCurrentSession();
  SchoolDetails schDtl=new SchoolDetails();
  schDtl.setSchoolAddress("Richmond College,Richmond Hill,Galle");
  School richmond=new School();
  richmond.setSchoolName("richmond College Galle");

Result :


Post a Comment

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