64 lines
2.9 KiB
Java
64 lines
2.9 KiB
Java
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, ctxfield.getName());
|
|
}
|
|
}
|
|
|
|
static void initEntity(ModelBuilder mb, Class<? extends SerializableObject> clazz, String name) {
|
|
var entity = mb.getOrCreateEntity(clazz);
|
|
entity.setName(name);
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|