简体   繁体   English

在Java中实现对象列表的最佳实践

[英]Best practices implementing list of objects in Java

I'm currently working on improving some old uni assignments moving them from serializable files to any other form of storage, mainly SQL Databases. 我目前正在改进一些旧的uni分配,将它们从可序列化的文件移动到任何其他形式的存储,主要是SQL数据库。 I understand the concept of relational database design and the similarities with OOP Classes, however, I'm not entirely sure how to approach this issue from an OOP design perspective. 我了解关系数据库设计的概念以及与OOP类的相似之处,但是,我不确定如何从OOP设计的角度解决这个问题。

Right now I have a Hotel class with a List of Rooms as property, each Room has a list of Guests as property ( full code here ) 现在我有一个酒店类,其中有“房间列表”作为属性,每个房间都有一个“客人列表”作为属性( 此处有完整代码

Back when using files I could mark these classes with the Serializable interface and store the parent object in a single file. 返回使用文件时,我可以使用Serializable接口标记这些类,并将父对象存储在单个文件中。 But when using relational DB, I store each list as a single table and use separate queries to obtain the corresponding results. 但是,当使用关系数据库时,我将每个列表存储为单个表,并使用单独的查询来获取相应的结果。 Same goes for the add() operation: with databases, I can do something like Guest.add() and add all the required fields directly to the database, whereas with my current design I need to call Room.getGuestList().add() (or a similar approach). add()操作也是如此:对于数据库,我可以执行Guest.add() ,并将所有必填字段直接添加到数据库中,而对于我目前的设计,我需要调用Room.getGuestList().add() (或类似的方法)。

I totally understand that neither of both approaches is ideal, as both classes should be only worried about storing the data and not about the implementation of an add method, but even if I separate this in a single class, shall I still define a List property within each class? 我完全理解这两种方法都不是理想的,因为两个类都应该只担心存储数据,而不要担心add方法的实现,但是即使我将其分隔在单个类中,我仍然应该定义List属性每个班级?

I'm pretty sure I'm missing a design pattern here, but I cannot find the one that would solve this problem or maybe it's just that I've been taught wrong. 我很确定我在这里缺少一种设计模式,但是我找不到能解决此问题的设计模式,或者仅仅是因为我被教导错误。

Thanks for your answers 谢谢你的回答

Edit: I've decided thanks to the answers provided to transform my implementation following the DAO pattern as explained in this question and the Oracle documentation . 编辑:我已经决定要感谢提供的答案,以按照此问题Oracle文档中所述的DAO模式转换实现。

Normally you would have 3 tables: hotels, rooms, guests. 通常,您将拥有3张桌子:酒店,客房,客人。 Rooms would have relation to hotel (hotel id) and guest would have relation to room(room id). 房间将与酒店(酒店ID)相关,而客人将与房间(房间ID)相关。 That's it. 而已。 Those relations can be easily reflected in OOP using some sort of ORM. 可以使用某种ORM在OOP中轻松反映这些关系。 JPA with Hibernate is an excellent example. Hibernate的JPA是一个很好的例子。 Check that out. 检查出。 You will be able to get hotel, its rooms and all guests of hotel just like you described without using a single SQL query in your code. 您将能够像您描述的那样获得旅馆,旅馆的房间以及旅馆的所有客人,而无需在代码中使用单个SQL查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM