gpt4 book ai didi

hibernate - 使用 hibernate 将值插入多个表

转载 作者:行者123 更新时间:2023-12-01 22:44:36 24 4
gpt4 key购买 nike

我有现有的表 hotelhotel_services

hotel table contains:
hotel_id
hotel_name

hotel_services contains:
hotel_id
hotel_service_name

每家酒店都可以提供多种服务,因此在我的表单中,用户可以一次输入任意数量的服务。

例如:

hotel name: HOTEL1
hotel_services:
1. hotel_service1
2. hotel_service2
3. hotel_service3

我的问题是我应该如何在 hibernate 状态下将所有数据插入到它们各自的表(酒店和酒店服务表)中。

谢谢你的帮助..

最佳答案

您所描述的是 HotelServices 之间的基本 OneToMany 关系,映射看起来像这样(我将使用注释将其映射为双向关联):

@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
}

这是一个演示如何使用它的片段:

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();

要更进一步(因为我不会在这个答案中解释所有内容),请查看:

关于hibernate - 使用 hibernate 将值插入多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3921806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com