How to cascade foreign key delete using ormlite in android

I use ormlite in android and have successfully created the tables and perform various operations using the DAO.

But I am stuck in deleting a row of foreign keys if the primary key is deleted from the main table.

I have two tables named Parent and child. A parent has more than one child, so I associated it with a foreign key.

The code:
Parent table:

@DatabaseField(id = true) private Integer id; @ForeignCollectionField(eager = false) private ForeignCollection<Child> childCollection; 

Children table:

 @DatabaseField(id = true) private Integer id; @DatabaseField(foreign = true, foreignAutoRefresh = true, canBeNull = false, index = true, columnDefinition = "INTEGER REFERENCES parent(id) ON DELETE CASCADE") private Parent parent; 

Now, if I delete the parent row for a specific identifier, this does not remove the children from the child table.

 public void deleteById(Integer parentId) { try { Dao<Parent, Integer> parentDao = databaseHelper.getParentDao(); parentDao .deleteById(parentId); } catch (SQLException e) { e.printStackTrace(); } } 

I beg you if I am mistaken. I tried Google many times, but no luck.

+5
source share
2 answers

You may have already found a solution, but someone may need it. according to the source code of BaseForeignCollection solution could be as follows:

 parent.getChildren().clear(); Dao<Parent, Integer> parentDao = databaseHelper.getParentDao(); parentDao.delete(parent); 

Actually, you can implement your own dao for the parent and override the delete method as follows:

 @Override public int delete(final Parent data) throws SQLException { data.getChildren().clear(); return super.delete(data); } 

This would probably be sufficient in such cases.

+2
source

You should use constraint , for example:

 @DatabaseField ( foreign = true, foreignAutoRefresh = true, canBeNull = false, index = true, columnDefinition = "INTEGER CONSTRAINT FK_NAME REFERENCES parent(id) ON DELETE CASCADE" ) private Parent parent; 

PS I know that it is dead aging 3 years :)

+2
source

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


All Articles