added foreign keys

This commit is contained in:
wea_ondara
2022-07-24 13:13:13 +02:00
parent 7ac7799d57
commit ff4385aa5c
48 changed files with 2139 additions and 549 deletions

View File

@@ -0,0 +1,62 @@
package jef.model;
import jef.DbSet;
import jef.model.annotations.Clazz;
import jef.model.annotations.Transient;
import jef.serializable.SerializableObject;
import java.lang.reflect.Field;
import java.util.Collection;
class EntityInitializer {
static void initEntities(ModelBuilder mb, Class<? extends DbContext> context) {
for (Field ctxfield : context.getDeclaredFields()) {
if (!DbSet.class.isAssignableFrom(ctxfield.getType())) {
continue;
}
Clazz clazzAnnotation = ctxfield.getAnnotation(Clazz.class);
if (clazzAnnotation == null) {
throw new ModelException("DbSet " + ctxfield.getName() + " is missing the " + Clazz.class.getSimpleName() + " annotation");
}
var dbsetClazz = (Class<? extends SerializableObject>) clazzAnnotation.clazz();
initEntity(mb, dbsetClazz);
}
}
static void initEntity(ModelBuilder mb, Class<? extends SerializableObject> clazz) {
var entity = mb.getOrCreateEntity(clazz);
var fields = ReflectionUtil.getFieldsRecursive(clazz);
for (var f : fields) {
if (f.getAnnotationsByType(Transient.class).length > 0) {
continue;
}
if (Collection.class.isAssignableFrom(f.getType())) {
//find a Collection field with the same Model
//e.g. class Entity { @Clazz(Entity2.class) List<Entity2> ent; @Clazz(Entity2.class) Set<Entity2> ent2; }
var clazzAnnotation = f.getAnnotationsByType(Clazz.class);
if (clazzAnnotation.length == 0) {
throw new ModelException("Field " + f.getClass().getSimpleName() + "::" + f.getName() + " is missing the " + Clazz.class.getSimpleName() + " annotation");
}
var fClazz = clazzAnnotation[0].clazz();
var foundCollection = entity.getFields().stream()
.filter(e -> Collection.class.isAssignableFrom(e.getType())
&& e.isModelField()
&& e.getField().getAnnotationsByType(Clazz.class).length > 0
&& e.getField().getAnnotationsByType(Clazz.class)[0].clazz() == fClazz)
.findFirst();
if (foundCollection.isPresent()) {
throw new ModelException("Model " + entity.getType().getSimpleName() + " multiple contains a 1 to N relation with type " + fClazz.getSimpleName());
}
entity.getOrCreateField(f);
} else if (SerializableObject.class.isAssignableFrom(f.getType())) {
entity.getOrCreateField(f);
} else {
var dbField = entity.getOrCreateField(f);
if (f.getType().isPrimitive()) {
dbField.setNotNull(true);
}
}
}
}
}