Ensuring data integrity with OrmLite

I have a Question class that contains a list of Answer objects. In my POJOs, I present this in my Question class as:

 @ForeignCollectionField private ForeignCollection<Answer> answers; 

and in my response class this link is declared as:

 @DatabaseField(foreign = true, canBeNull=false) private Question question; 

I expected ORMlite to throw an exception if I try to save an Answer that refers to a Question that has not yet been saved to the database. However, this does not seem to be happening. I can save Answer objects as I want, without saving the Question reference objects. I checked that Answer saved without saving questions when searching in my database using SQLliteBrowser . This violates the integrity of the data, since when I restart my program, db now contains answers that refer to non-existing questions.

Is there any way to provide this? Thanks to my experience at Hibernate, it will not allow you to save the Child object without first saving the specified Parent object.

+4
source share
1 answer

Add the following columnDefinition to the field and it will not allow you to create an object if its external identifier does not exist.

 @DatabaseField(foreign = true, canBeNull=false, columnDefinition = "integer references question(id) on delete cascade") private Question question; 

See also other topics: Creating foreign key constraints in ORMLite in SQLite

+7
source

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


All Articles