Powered by Blogger.

Friday, 12 December 2014

Delete Data From Many-to-many Relationship

By Shambhu Kumar  |  07:25 No comments


CustomerEntity class


@Entity(name = "CUSTOMER")
public class CustomerEntity {
   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customerid-gen")
   @SequenceGenerator(name = "customerid-gen", sequenceName = "CUSTOMER_SEQ"
      allocationSize = 1, initialValue = 0)

   @Column(name = "CUSTOMER_ID")
   private Integer id;

   private String customerName;

   @ManyToMany(cascade ={CascadeType.ALL})
   @JoinTable(name = "CUST_PHONE"
      joinColumns = @JoinColumn(name = "CUSTOMER_ID"
                                 referencedColumnName = "CUSTOMER_ID"), 
   inverseJoinColumns = @JoinColumn(name = "PHONE_ID"
                                 referencedColumnName = "PHONE_ID"))
   private List<PhoneNumberEntity> phones = new ArrayList<PhoneNumberEntity>();

}


PhoneNumberEntity class
@Entity(name = "PHONE")
public class PhoneNumberEntity {
   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "phoneid-gen")
   @SequenceGenerator(name = "phoneid-gen", sequenceName = "PHONE_SEQ"
      allocationSize = 1, initialValue = 0)
   @Column(name = "PHONE_ID")
   private Integer id;

   private String phNumber;

   @ManyToMany(cascade ={CascadeType.ALL})
   @JoinTable(name = "CUST_PHONE", joinColumns = @JoinColumn(name = "PHONE_ID",
                   referencedColumnName = "PHONE_ID"),
              inverseJoinColumns = @JoinColumn(name = "CUSTOMER_ID"
                     referencedColumnName = "CUSTOMER_ID"))
   private List<CustomerEntity> customers;

}


Testing class

CustomerEntity entity = new CustomerEntity("Shambhu");
entity.getPhones().add(new PhoneNumberEntity("(8837199181"));
entity.getPhones().add(new PhoneNumberEntity("(8981518899"));
Integer id = emService.persistCustomer(entity);
             
CustomerEntity customerEntity=emService.findCustomerById(id);
             
List<PhoneNumberEntity> phones= customerEntity.getPhones();
             
for(PhoneNumberEntity entity2:phones){
       System.out.println("Deleting phone id :"+entity2.getId());
       emService.deletePhone(entity2.getId());
       //break;

}


Author: Shambhu Kumar

Hello, I am Author, decode to know more: In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet.

0 comments:

Recent Articles

© 2014 Learning Java. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates
TOP