4

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

@ForeignCollectionField 
private ForeignCollection<Answer> answers;

and in my Answer class this relationship is declared as:

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

I had expected that ORMlite would throw an exception if I tried to persist an Answer which referenced a Question that had not yet been persisted to the database. However, this does not appear to happen. I can persist Answer objects as I please without saving the referenced Question objects. I verified the Answers are being saved with no questions being saved by looking in my database using SQLliteBrowser. This breaks my data integrity as when I restart my program the db now contains Answers that reference non existing questions.

Is there any way to enforce this? With my experience in Hibernate it will not allow you to save the Child object without first saving the referenced "Parent" object.

Gray
  • 115,027
  • 24
  • 293
  • 354
MayoMan
  • 4,757
  • 10
  • 53
  • 85

1 Answers1

7

Add the following columnDefinition to your field and it will not allow the object to be created if the foreign ID it references does not exist.

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

See also other thread: Creating foreign key constraints in ORMLite under SQLite

Community
  • 1
  • 1
MayoMan
  • 4,757
  • 10
  • 53
  • 85