如何使用 hibernate 将这个复杂的对象持久保存到数据库中?
后端mysql中有数据库表对应这些类,并相应定义了外键。如果我需要将这些关系放在这里,请告诉我。
class Itinerary {
Airport Departure;
Airport Arrival;
Airline flight;
}
class Airport{
int idAirport;
String terminal;
City city;
}
class City{
int idCity;
String name;
}
class Airline{
int idAirline;
String flightNumber;
}
我使用这样的东西: http://pastebin.com/YzYMTBg3 来构建行程对象。这就是让我困惑的地方,我不知道使用 hibernate 作为我的 ORM 来处理这个问题的好方法是什么。
AirSegmentBuilder segmentBuilder = new AirSegmentBuilder();
segmentBuilder.addDepartureAirport("JFK");
segmentBuilder.addArrivalAirport("SFO");
我正在尝试将出发和到达机场(对象)添加到我的行程中。这些对象依次在数据库中保留为:
机场:
id | name | terminal
1 | JFK | 1
2 | SFO | B1
因此,当我需要将这些机场添加到我的行程中时,我是否需要首先使用基于名称的查询来获取机场对象?然后将这些对象附加到行程中?一旦我构建了行程对象并使用 hibernate 将其保存到数据库中,它是否能够正确获取外键?
There are database tables in mysql at the backend corresponding to these classes with Foreign Keys defined accordingly. Let me know if I need to put those relations here.
class Itinerary {
Airport Departure;
Airport Arrival;
Airline flight;
}
class Airport{
int idAirport;
String terminal;
City city;
}
class City{
int idCity;
String name;
}
class Airline{
int idAirline;
String flightNumber;
}
I use something like this: http://pastebin.com/YzYMTBg3 to build an itinerary object. This is what is puzzling me, and I don't know what is a good way to handle this using hibernate as my ORM.
AirSegmentBuilder segmentBuilder = new AirSegmentBuilder();
segmentBuilder.addDepartureAirport("JFK");
segmentBuilder.addArrivalAirport("SFO");
I am trying to add departure and arrival airport (objects) to my itinerary here. These objects in turn persist in database as:
Airport:
id | name | terminal
1 | JFK | 1
2 | SFO | B1
So when I need to add these airports to my itinerary, do I need to fetch the airport objects first using a query based on name?; and then attach these objects to itinerary? Once I have the itinerary object built and save it to the database using hibernate, would it be able to pick up the foreign keys correctly ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您正在使用 xml 来配置您的 hibernate 内容。
您可以像这样编写 Itinerary.hbm.xml 来实现您的目标:
其中机场、航空公司和行程是数据库中的表。
希望这会有所帮助...
注意 - 这只是一个例子。您可能需要相应地更新您的 Bean。
Assuming you are using xml to configure your hibernate stuff.
You may write your Itinerary.hbm.xml like this to achieve your goal :
where Airport, Airline and Itinerary are the tables in your DB.
Hope this helps...
Note - This is just a kind of example. You may need to update your beans accordingly.