Storing a HashMap in an SQL database

2020-02-11 04:01发布

问题:

How do you store a HashMap inside of an SQL database? Also, how would you load that HashMap from a SQL database back into an instance of a HashMap?

Okay, this is what I'm doing. I have a database to store the player data for my game. It has a table containing their usernames and passwords. Each player has a HashMap that stores their properties. I need to store that HashMap in the database along with it's respective user.

回答1:

You need a 3 column table

user,

key,

value

Would then look like

"user 1", "property1", "value1"

"user 1", "property2", "value2"

"user 2", "property1", "value1"

"user 3", "property1", "value1"

"user 3", "property2", "value2"

You would then just read the data back in and look round the user field to rebuild each has table.



回答2:

If you want to stick key-value you can, however, you've to make sure the keys and values are strings and can fit in the column definition. Here is an example:

mysql> create table hashmap (k varchar(200), v varchar(200));
Query OK, 0 rows affected (0.24 sec)

mysql> insert into hashmap values ('key','value');
Query OK, 1 row affected (0.02 sec)

mysql> select * from hashmap;
+------+-------+
| k    | v     |
+------+-------+
| key  | value |
+------+-------+
1 row in set (0.00 sec)

Additionally, you can unique index the column k which holds the keys so your lookups are constant just like a hashmap, and you can replace the old value by using ON DUPLICATE KEY UPDATE v = new_value.. I am assuming you're using MySQL for the ON DUPLICATE KEY part.



回答3:

Each entry in the HashMap is like a row in your table. You would end up having a separate table for each HashMap (probably).

Your K parameter in your map should be enforced as a unique key on your table, and indexed.

Keep in mind that storing these objects may require more than one column each. For example, you may have a Point object as your key, so you'd need a column x and column y, and an index on uniqueness for x and y pairs.



回答4:

HashMap is data structure, You can store data residing in it.

Create a table emulating key value pair. iterate through keys of map and store it in DB.



标签: java sql hashmap