What you're describing is a basic OneToMany
relation between an Hotel
and Services
and the mapping would look like this (I'll map it as a bidirectional association, using annotations):
@Entity
public class Hotel {
@Id @GeneratedValue
private Long id;
@OneToMany(cascade=ALL, mappedBy="hotel")
Set<Service> services = new HashSet<Service>();
// other attributes, getters, setters
// method to manage the bidirectional association
public void addToServices(Service service) {
this.services.add(service);
service.setHotel(this);
}
@Entity
public class Service {
@Id @GeneratedValue
private Long id;
@ManyToOne
private Hotel hotel;
// getters, setters, equals, hashCode
}
And here is a snippet demonstrating how to use this:
SessionFactory sf = HibernateUtil.getSessionFactory(); // this is a custom utility class
Session session = sf.openSession();
session.beginTransaction();
Hotel hotel = new Hotel();
Service s1 = new Service();
Service s2 = new Service();
hotel.addToServices(s1);
hotel.addToServices(s2);
session.persist(hotel);
session.getTransaction().commit();
session.close();
To go further (because I won't explain everything in this answer), have a look at: