drop referencing foreign keys when primary key of entity builder is dropped

This commit is contained in:
wea_ondara
2022-09-08 17:05:50 +02:00
parent ad29897cd8
commit dff7dd4229
2 changed files with 68 additions and 1 deletions

View File

@@ -144,11 +144,17 @@ public class KeyBuilder<T extends SerializableObject> {
isPrimaryKey(true); isPrimaryKey(true);
} }
public void isPrimaryKey(boolean primary) {//TODO foreign key integrity public void isPrimaryKey(boolean primary) {
if (primary) { if (primary) {
entity.setPrimaryKey(new PrimaryKeyConstraint(entity, fields)); entity.setPrimaryKey(new PrimaryKeyConstraint(entity, fields));
} else { } else {
entity.setPrimaryKey(null); entity.setPrimaryKey(null);
//drop referencing foreign keys
modelBuilder.entities().forEach(e -> {
var remove = e.getEntity().getForeignKeys().stream().filter(fk -> fk.getReferencedEntity() == this.entity).toList();
remove.forEach(fk -> e.getEntity().dropForeignKey(fk));
});
} }
} }

View File

@@ -0,0 +1,61 @@
package jef.model;
import jef.DbSet;
import jef.model.annotations.Clazz;
import jef.model.annotations.Id;
import jef.serializable.SerializableObject;
import lombok.Getter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class KeyBuilderPrimaryDropRelatedForeignKeyDropTest {
@Test
public void test() {
var mb = ModelBuilder.from(Ctx.class);
assertEquals(1, mb.getEntity(TestClass3.class).getForeignKeys().size());
assertEquals(1, mb.getEntity(TestClass2.class).getForeignKeys().size());
assertEquals(0, mb.getEntity(TestClass.class).getForeignKeys().size());
mb.entity(TestClass.class).hasOne(e -> e.i).isPrimaryKey(false);
assertEquals(1, mb.getEntity(TestClass3.class).getForeignKeys().size());
assertEquals(0, mb.getEntity(TestClass2.class).getForeignKeys().size());
assertEquals(0, mb.getEntity(TestClass.class).getForeignKeys().size());
}
public static class Ctx extends DbContext {
@Clazz(TestClass.class)
private DbSet<TestClass> objects1;
@Clazz(TestClass2.class)
private DbSet<TestClass2> objects2;
@Clazz(TestClass3.class)
private DbSet<TestClass2> objects3;
}
@Getter
public static class TestClass3 extends SerializableObject {
@Id
public int i3 = 1;
private TestClass2 nested2;
}
@Getter
public static class TestClass2 extends SerializableObject {
@Id
public int i2 = 1;
private TestClass nested;
}
@Getter
public static class TestClass extends SerializableObject {
@Id
public int i = 1;
public Object o = new Object();
public double d;
public float f;
public long l;
}
}