inserting values into multiple tables using hibernate
i have existing tables hotel and hotel_services.
hotel table contains:
hotel_id
hotel_name
hotel_services contains:
hotel_id
hotel_service_name
each hotel can offer several services, so in my form user could enter as many services as he wants at a time.
so for instance:
hotel name: HOTEL1
hotel_services:
1. hotel_service1
2. hotel_service2
3. hotel_service3
My question is how should i do it in hibernate in such a way that i'll be able to insert all the data into their respective tables(which are hotels and hotel_services tables).
thanks for the h开发者_高级运维elp..
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:
- Hibernate Getting Started Guide (covers the Native API with XML mappings, the Native API with annotations, the JPA API)
- Hibernate Core Reference Guide
- Chapter 1. Tutorial
精彩评论