package com.pojo; import java.util.Set; import javax.persistence.Entity; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @Entity @Table(name = "Person") public class Person implements java.io.Serializable { private Set<Address> addresses; @OneToMany(mappedBy = "person") public Set<Address> getAddresses() { return addresses; } public void setAddresses(Set<Address> addresses) { this.addresses = addresses; } }
package com.pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "Address") public class Address { private Person person; @ManyToOne @JoinColumn(name = "person_id") public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
Person person = new Person(); Address address1 = new Address(); session.save(person); session.save(address1);
2) CascadeType.ALL : With this cascade type when a Parent is saved, updated, deleted Child will also gets saved, updated, deleted. No need to explicitly save or update or delete the childrens into the session.
private Set<Address> addresses; @OneToMany(mappedBy = "person") @Cascade( { CascadeType.ALL}) public Set<Address> getAddresses() { return addresses; } public void setAddresses(Set<Address> addresses) { this.addresses = addresses; }
Person person = new Person(); Address address1 = new Address(); Address address2 = new Address(); person.setAddresses(new HashSet<Address>()); person.getAddresses().add(address1); person.getAddresses().add(address2); session.save(person);
List<Person> persons = session.createQuery( "from Person where" + " person_Id = 2").list(); for (Person person : persons) { session.delete(person); }
Very useful...😊
ReplyDelete