简体   繁体   中英

Java - Store HashSet in mysql

How would I go about storing a HashSet with an unknown size in a mysql table. I know I can loop through it and store it into a longtext field.

However when I retrieve that field and store it into a string temporarily it will use extra memory to store that huge string of info.

Is there any easy way to store a HashSet?

A SQL table with indexed columns is basically a hash set.

You shouldn't try to store (persist) a binary representation of a HashSet in a table. You should store (persist) the data of your HashSet as rows and columns and then read that data into your HashSet on the Java side.

In other words, you should be using a database to store your data directly rather than saving a serialized representation of a Java collection that holds your data. That's what a database is meant to do... store/persist data in a structured, consistent manner. If all you really need to do is to serialize a HashSet then why bother with a database at all?

I would turn it into JSON and store it as text.

There are libraries out there that convert to and from JSON with ease - eg googles gson

Yes. Each element in a separate record in a table with foreign key to the 'parent' table. Yhay is how JPA handles it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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