New Annotations Used :
- @Table(name="Customer") : Main table (1st table)
- @SecondaryTable(name="CustomerDetail") : Secondary table
- @Column(table="CustomerDetail") : Mark the fields which are going to maintain in the second table
Customer.java
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.SecondaryTable; import javax.persistence.Table; @Entity @Table(name="Customer") @SecondaryTable(name="CustomerDetail") public class Customer { private int customerID; private String customerName; private String customerAddr; private int creditScore; private int rewadrsPoints; @Id @GeneratedValue public int getCustomerID() { return customerID; } public void setCustomerID(int customerID) { this.customerID = customerID; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } @Column(table="CustomerDetail") public String getCustomerAddr() { return customerAddr; } public void setCustomerAddr(String customerAddr) { this.customerAddr = customerAddr; } @Column(table="CustomerDetail") public int getCreditScore() { return creditScore; } public void setCreditScore(int creditScore) { this.creditScore = creditScore; } @Column(table="CustomerDetail") public int getRewadrsPoints() { return rewadrsPoints; } public void setRewadrsPoints(int rewadrsPoints) { this.rewadrsPoints = rewadrsPoints; } }Now we have to persist those class
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(Customer.class); config.configure("hibernate.cfg.xml"); new SchemaExport(config).create(true, true); SessionFactory factory=config.buildSessionFactory(); Session session=factory.getCurrentSession(); session.beginTransaction(); Customer cus1=new Customer(); cus1.setCreditScore(120); cus1.setCustomerAddr("221C,Samanala Mawatha,Malabe"); cus1.setCustomerName("Kanishka Dilshan"); cus1.setRewadrsPoints(23); Customer cus2=new Customer(); cus2.setCreditScore(100); cus2.setCustomerAddr("221C,Sivla Rd,Kaduwela"); cus2.setCustomerName("Maduranga Sampath"); cus2.setRewadrsPoints(52); session.saveOrUpdate(cus1); session.saveOrUpdate(cus2); session.getTransaction().commit(); } }
Result :
0 comments:
Post a Comment