First of I am new to ORMLite. I would like my model class to have a field which is a list of strings, that would eventually hold a list of tags for my model object.
Which ORMLite annotations should I use?
Firstly I don't want to have a table of all tags, and then use the @ForeignCollectionField
.
Also I thought of using the @DatabaseField(dataType=DataType.SERIALIZABLE)
annotation, but it turns out that List<String>
doesn't implement the Serializable
interface.
What are your suggestions?
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; }