Having a list of strings represented in a database using ORMLite

让人想犯罪 __ 提交于 2019-12-04 13:02:30

First of all, List doesn't implement Serializable but ArrayList certainly does as well as most of the common collection implementations. But storing a huge list is probably not the best of doing this from a pure object model standpoint.

So why don't you want to have a table of all tags? That's the best way from a pure model standpoint. It will require a 2nd query if you need them every time. That's the way hibernate would store a list or array of tags.


After reading your comment @creen, I still think you do want a table of tags. Your model class would then have:

@ForeignCollectionField
Collection<Tag> tags;

The tags table would not have a single tag named "red" with multiple model classes referring to it but multiple "red" entries. It would look like:

model_id    name
1           "red"
1           "blue"
2           "red"
3           "blue"
3           "black"

Whenever you are removing the model object, you would first do a tags.clear(); which would remove all of the tags associated with that model from the tags table. You would not have to do any extra cleanup or anything.

No need to go for @ForeignCollectionField for simple String Array

Change your code

@DatabaseField(dataType=DataType.SERIALIZABLE) 
List<String> users;

to

@DatabaseField(dataType = DataType.SERIALIZABLE)
String[] users;

Database doesn't want to store dynamically grow able arrays. That is the reason it allows only static array like string[] and not List.

I added two properties... one that gets written to the database as a csv string and the other that translates this:

[Ignore]
public List<string> Roles
{
    get
    {
        return new List<string>(RolesCsv.Split(new char[] { ',' }));
    }
    set
    {
        RolesCsv = string.Join(",", value);
    }
}
public string RolesCsv { get; set; }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!