org.zodiac.fastorm.rdb.mapping.DefaultEntityColumnMapping Maven / Gradle / Ivy
The newest version!
package org.zodiac.fastorm.rdb.mapping;
import org.zodiac.fastorm.rdb.metadata.RDBColumnMetadata;
import org.zodiac.fastorm.rdb.metadata.TableOrViewMetadata;
import org.zodiac.sdk.toolkit.util.ExceptionUtil;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
public class DefaultEntityColumnMapping implements EntityColumnMapping {
private final Map propertyColumnMapping = new LinkedHashMap<>();
private final Map columnPropertyMapping = new LinkedHashMap<>();
private final String id;
private final String name;
private final TableOrViewMetadata table;
private final Class> entityType;
private final Constructor> constructor;
public DefaultEntityColumnMapping(TableOrViewMetadata table, Class> entityType) {
this.id = getType().createFeatureId(entityType);
this.name = getType().getName() + ":" + entityType.getSimpleName();
this.table = table;
this.entityType = entityType;
Constructor> c = null;
try {
c = this.entityType.getConstructor();
} catch (NoSuchMethodException | SecurityException e) {
ExceptionUtil.chuck(e);
}
this.constructor = c;
}
public DefaultEntityColumnMapping addMapping(String column, String property) {
columnPropertyMapping.put(column, property);
propertyColumnMapping.put(property, column);
return this;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public TableOrViewMetadata getTable() {
return table;
}
public Class> getEntityType() {
return entityType;
}
@Override
public Optional getColumnByProperty(String property) {
if (property.contains(".")) {
String[] key = property.split("[.]");
return table
.getForeignKey(key[0])
.flatMap(keyMetadata -> keyMetadata.getTarget().getColumn(key[1]));
}
return Optional
.ofNullable(propertyColumnMapping.get(property))
.flatMap(table::getColumn);
}
@Override
public Optional getPropertyByColumnName(String columnName) {
return Optional
.ofNullable(columnPropertyMapping.get(columnName));
}
@Override
public Optional getColumnByName(String columnName) {
if (columnName.contains(".")) {
String[] key = columnName.split("[.]");
return table.getForeignKey(key[0])
.flatMap(keyMetadata -> keyMetadata.getTarget().getColumn(key[1]));
}
return table.getColumn(columnName);
}
@Override
public void reload() {
for (RDBColumnMetadata column : table.getColumns()) {
addMapping(column.getName(),column.getAlias());
}
}
@Override
public Map getColumnPropertyMapping() {
return Collections.unmodifiableMap(columnPropertyMapping);
}
@Override
public Object newInstance() {
Object result = null;
try {
return constructor.newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
ExceptionUtil.chuck(e);
}
return result;
}
}