While working with collection if you want the details to be stored in a seperate table using @ElementCollection solves the purpose

UserDetails.java

 public class UserDetails {
  @ElementCollection
  private List<Address> arrList = new ArrayList<Address>();

 }

Address.java

@Embeddable
public class Address 
{
  private String DoorNo;
  private String Street;
  private String Location;
  private String Pincode;
  .
  .
  .
 }

createTables.java

public class CreateTables {   
  public static void main(String[] args) 
  {
    UserDetails objUserDetail1 =  new UserDetails();

    Address objAddr = new Address();
    objAddr.setDoorNo("13");
    objAddr.setStreetName("Poes Road");
    objAddr.setLocation("Teynampet");
    objAddr.setPincode("600018");
    
    
    Address objAddr2 = new Address();
    objAddr2.setDoorNo("256");
    objAddr2.setStreetName("Sriman Srinivasan Road");
    objAddr2.setLocation("Alwarpet");
    objAddr2.setPincode("600018");
    
    objUserDetail1.getArrList().add(objAddr);
    objUserDetail1.getArrList().add(objAddr2);
  }
}

Giving Names to Joined Tables

  • New Table will be created under USER_ADDRESS Name
  • joinColumns decides which column should be used for joining two tables

Format for Join Table

  @JoinTable(name="JOIN_TABLE_DESIRED_NAME", 
	     joinColumns= @JoinColumn(name="userId"))
  @JoinTable(name="USER_ADDRESS", 
	     joinColumns= @JoinColumn(name="userId"))
  private Set<Address> addressSet = new HashSet();
  .
  .

Comments are closed.