How to Access Entity collection in Hibernate?

508 views Asked by At
@Entity 
@Table (name="USER_DETAIL")
public class AccountBean {

@Id @GeneratedValue
private int id;                                         
private String name;
private String description;  

@OneToMany
private List<Address> listOfAddress = new ArrayList<Address>();

//with all getter and setter 
}

Address class:

@Entity
public class Address {

@Id
@GeneratedValue
private int addId;
@Column (name="HOUSE_NUMBER")
private int houseNumber;
@Column (name="CITY_NAME")
private String city;
@Column (name="STATE_NAME")
private String state;
@Column (name="PIN_ZIP")    
private int zip;
 // with all getter setter 
}

How to access collection of Address data from AccountBean Entity class while all data will be saved in AccountBean Entity class only and Address Entity class associated with Accountbean class

1

There are 1 answers

0
iullianr On

Currently you don't have Address Entity associated with AccountBean only the other way around (so it is one-directional relationship, as defined in your code). So, you define a field of type AccountBean with a @ManyToOne relationship on it, and then you enhanced your @OneToMany relationship like this @OneToMany(mappedBy = "Address>", cascade = {CascadeType.ALL})

Now when you retrieve an object of type AccountBean from DB, it will automatically have the List of Address entities populated (if any defined). When you add a new Address to the list, and merge the AccountBean, it will automatically persist the new Address entity and associate it to AccountBean object