简体   繁体   English

如何在SQL数据库中存储我的自定义对象

[英]How to store my custom object in sql database

I have a class Account which has a name, email address, phone number and ArrayList of Vehicles, where Vehicles is another class with Strings make, model and int year. 我有一个Account类,它具有名称,电子邮件地址,电话号码和Vehicles的ArrayList,其中Vehicles是具有Strings make,model和int year的另一个类。 I want to store Accounts in a database. 我想将帐户存储在数据库中。 I am able to store the name, email address and phone number with no problems, but am unsure how to store the ArrayList of Vehicles. 我能够毫无问题地存储名称,电子邮件地址和电话号码,但是不确定如何存储车辆的ArrayList。 The two options i found from looking online were JSONObject/Array and serialization. 我从网上查找的两个选项是JSONObject / Array和序列化。 However, I failed to convert the JSONObject back to my Vehicle Object when bringing it back out of the database. 但是,将JSONObject从数据库中带回时,我无法将其转换回我的Vehicle Object。 And serialization I didn't fully understand and couldn't find much online. 而且我还不太了解序列化,因此在网上找不到很多。 It seemed all the tutorials serialized objects to files and not databases. 似乎所有教程都将对象序列化为文件而不是数据库。 Any help on either method to store my data in the database would be helpful, or a better way of doing it? 在将数据存储在数据库中的任何一种方法上有任何帮助将是有帮助的,或者是做得更好的方法?

Thanks. 谢谢。

If the Vehicles can only associated with a single Account, then I'd add the Account as a foreign key to the Vehicles table (assuming you have a Vehicles table, if not you'll need to create one). 如果Vehicles只能与一个帐户关联,那么我会将帐户作为外键添加到Vehicles表中(假设您有一个Vehicles表,如果没有,则需要创建一个)。

If Vehicles can be associated with multiple accounts then I'd make an intermediary table that tracks the relationships between Accounts and Vehicles, so it would just have two fields: account_id, vehicle_id. 如果Vehicles可以与多个帐户关联,那么我将创建一个中间表来跟踪Accounts和Vehicles之间的关系,因此它将只有两个字段:account_id,vehicle_id。 (Once again requiring a Vehicles table) (再次需要车辆表)

I suppose you could serialize the ArrayList and store it in a field on the Accounts table...but that doesn't seem like a clean solution to me. 我想您可以序列化ArrayList并将其存储在Accounts表的一个字段中...但是,对于我来说,这似乎不是一个干净的解决方案。

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

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