When I create a bidirectional 1:n relationship as shown below, the generator does not use any FOREIGN KEY(...) constraints on the table.
entity customer = schema.addEntity("Customer");
customer.addIdProperty();
customer.addStringProperty("name").notNull();
Entity order = schema.addEntity("Order");
order.setTableName("ORDERS"); // "ORDER" is a reserved keyword
order.addIdProperty();
Property orderDate = order.addDateProperty("date").getProperty();
Property customerId = order.addLongProperty("customerId").notNull().getProperty();
order.addToOne(customer, customerId);
customer.addToMany(order, customerId);
Is this normal? Is it supposed to generate FOREIGN KEY(...) constraints in the table or is it only enforced at runtime through code?
I was stuck at the same issue while working on a project.
Going through the generated code by DaoGenerator, foreign key constraints are not generated even with the use of ToMany relation.
I tried appending the foreign key constraint manually in the query in each entity DAO, and yet it didn't solve the issue.
Referring the sqlite documentation, I found that the foreign key is not enforced by-default. You have to run query PRAGMA foreign_keys = ON;
for every connection created to database. I verified it from adb shell. Foreign key was enforced after running PRAGMA query.
Last problem was to find a place for this code in project so that it will execute for every session.
Solution is in DaoSession class generated by the DaoGenerator project
insert
if(!db.isReadOnly()){
db.execSQL("PRAGMA foreign_keys = ON;");
}
at the end of the constructor.
Don't forget to manually add foreign key constraint in create table queries for each DAO having foreign key property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With