Reputation: 703
I am using ormlite in android and has created tables successfully and perform the different operations using DAO.
But I have stuck in deleting the foreign keys row if primary key is deleted from the main table.
I have two tables named Parent and child. A parent have more than one child so I linked the child with foreign key.
Code:
Parent table:
@DatabaseField(id = true)
private Integer id;
@ForeignCollectionField(eager = false)
private ForeignCollection<Child> childCollection;
Child 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 am deleting parent row for a particular id then this is not deleting 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();
}
}
Please guide me, where I am doing wrong. I have tried and Google many times but no luck.
Upvotes: 5
Views: 4194
Reputation: 16363
You should use constraint
, like:
@DatabaseField (
foreign = true,
foreignAutoRefresh = true,
canBeNull = false,
index = true,
columnDefinition = "INTEGER CONSTRAINT FK_NAME REFERENCES parent(id) ON DELETE CASCADE"
)
private Parent parent;
P.S. I know it's dead post ageing 3 yrs :)
Upvotes: 3
Reputation: 2315
Probably you have already found solution, but someone may need this.
according to BaseForeignCollection
source code the solution may be following:
parent.getChildren().clear();
Dao<Parent, Integer> parentDao = databaseHelper.getParentDao();
parentDao.delete(parent);
Actually, you can implement your own dao for parent and override delete method like this:
@Override
public int delete(final Parent data) throws SQLException {
data.getChildren().clear();
return super.delete(data);
}
Probably, would be enough in such cases.
Upvotes: 3