2

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 help..

1
  • 1
    this is very basic ORM mapping, read some tutorials Commented Oct 13, 2010 at 8:31

1 Answer 1

7

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.