Person.java
import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; @Entity public class Person { private int personID; private String personName; private PersonDetails myPersonDetails; @Id @GeneratedValue public int getPersonID() { return personID; } public void setPersonID(int personID) { this.personID = personID; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @JoinColumn(name="pDetail_fk") public PersonDetails getMyPersonDetails() { return myPersonDetails; } public void setMyPersonDetails(PersonDetails myPersonDetails) { this.myPersonDetails = myPersonDetails; } }
PersonDetails.java
import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class PersonDetails { private int personDetailID; private String zipCode; private String job; private double income; private Person myPerson; @OneToOne(mappedBy="myPerson" , cascade=CascadeType.ALL) public Person getMyPerson() { return myPerson; } public void setMyPerson(Person myPerson) { this.myPerson = myPerson; } @Id @GeneratedValue @Column(name="datailid_pk ") public int getPersonDetailID() { return personDetailID; } public void setPersonDetailID(int personDetailID) { this.personDetailID = personDetailID; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public double getIncome() { return income; } public void setIncome(double income) { this.income = income; } }
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(Person.class); config.addAnnotatedClass(PersonDetails.class); config.configure("hibernate.cfg.xml"); new SchemaExport(config).create(true, true); SessionFactory factory=config.buildSessionFactory(); Session session=factory.getCurrentSession(); session.beginTransaction(); PersonDetails pd1=new PersonDetails(); pd1.setIncome(30000.65); pd1.setJob("Software Engineer"); pd1.setZipCode("201222"); Person p1=new Person(); p1.setPersonName("Kanishka Dilshan"); p1.setMyPersonDetails(pd1); session.save(p1); session.getTransaction().commit(); } }
0 comments:
Post a Comment