InterviewSolution
| 1. |
Can you tell something about one to many associations and how can we use them in Hibernate? |
|
Answer» The one-to-many association is the most commonly used which indicates that one object is linked/associated with multiple objects. For example, one PERSON can own multiple cars. Hibernate One To Many MappingIn Hibernate, we can achieve this by using @OnetoMany of JPA ANNOTATIONS in the model classes. Consider the above example of a person having multiple cars as SHOWN below: @Entity@Table(name="Person")PUBLIC class Person { //... @OneToMany(mappedBy="owner") private Set<Car> cars; // getters and setters}In the Person class, we have defined the car's property to have @OneToMany association. The Car class would have owned property that is used by the mappedBy variable in the Person class. The Car class is as shown below: @Entity@Table(name="Car")public class Car { // Other Properties @ManyToOne @JoinColumn(name="person_id", nullable=false) private Person owner; public Car() {} // getters and setters}@ManyToOne annotation indicates that many INSTANCES of an entity are mapped to one instance of another entity – many cars of one person. |
|