问题描述
我有现有的表 hotel 和 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.
例如:
hotel name: HOTEL1
hotel_services:
1. hotel_service1
2. hotel_service2
3. hotel_service3
我的问题是我应该如何在休眠状态下将所有数据插入各自的表(即hotel和hotel_services表)中.
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).
感谢您的帮助.
推荐答案
您要描述的是Hotel
和Services
之间的基本OneToMany
关系,映射看起来像这样(我将进行映射使用注释将其作为双向关联)
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入门指南》 (包含具有XML映射的Native API,具有批注的Native API,JPA API)
- Hibernate Core参考指南
- 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
这篇关于使用休眠将值插入多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!