Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform cascade deleting on foreign key using ormlite in android

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.

like image 329
Manoj Agarwal Avatar asked Oct 10 '14 12:10

Manoj Agarwal


2 Answers

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.

like image 163
MightySeal Avatar answered Nov 04 '22 12:11

MightySeal


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 :)

like image 33
Barmaley Avatar answered Nov 04 '22 14:11

Barmaley