Storing a HashMap in an SQL Database

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

Ok, this is what I do. I have a database for storing player data for my game. It has a table containing their usernames and passwords. Each player has a HashMap that retains its properties. I need to save this HashMap in the database with the corresponding user with it.

+6
source share
4 answers

You need a table with three columns

user

key

value

Then it will look like

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

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

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

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

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

Then you just read the data and looked at the user field to rebuild each table.

+10
source

If you want to adhere to the key value, you can, however, make sure that the keys and values ​​are strings and can fit into 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) 

In addition, you can uniquely index the column k that contains the keys, so your searches are constant like a hash map, and you can replace the old value with ON DUPLICATE KEY UPDATE v = new_value. . I assume that you are using MySQL for the ON DUPLICATE KEY .

+6
source

HashMap is a data structure, you can store the data in it.

Create a table emulating a pair of key values. iterate through the map keys and save them to the database.

+1
source

Each entry in the HashMap is like a row in your table. As a result, you will have a separate table for each HashMap (possibly).

Your parameter K on your map must be forced to enter as a unique key in your table and indexed.

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

+1
source

Source: https://habr.com/ru/post/886606/


All Articles