[FEAT] continue integration on Mongo

This commit is contained in:
Edouard DUPIN 2024-11-03 23:47:28 +01:00
parent d0baa61ead
commit 78dfb481fa
27 changed files with 224 additions and 125 deletions

View File

@ -12,6 +12,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import dev.morphia.annotations.Entity; import dev.morphia.annotations.Entity;
import dev.morphia.mapping.Mapper;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Nullable; import jakarta.annotation.Nullable;
import jakarta.persistence.Column; import jakarta.persistence.Column;
@ -76,7 +77,7 @@ public class AnnotationTools {
return clazz.getSimpleName(); return clazz.getSimpleName();
} }
final String tmp = ((Entity) annotation[0]).value(); final String tmp = ((Entity) annotation[0]).value();
if (tmp == null) { if (tmp == null || tmp.length() == 0 || Mapper.IGNORED_FIELDNAME.equals(tmp)) {
return clazz.getSimpleName(); return clazz.getSimpleName();
} }
return tmp; return tmp;

View File

@ -94,7 +94,7 @@ public abstract class DataAccess {
// check the compatibility of the id and the declared ID // check the compatibility of the id and the declared ID
final Class<?> typeClass = idField.getType(); final Class<?> typeClass = idField.getType();
if (idKey == null) { if (idKey == null) {
throw new DataAccessException("Try to identify the ID type and object wa null."); throw new DataAccessException("Try to identify the ID type and object was null.");
} }
if (idKey.getClass() != typeClass) { if (idKey.getClass() != typeClass) {
if (idKey.getClass() == Condition.class) { if (idKey.getClass() == Condition.class) {
@ -198,43 +198,43 @@ public abstract class DataAccess {
final byte[] dataByte = UuidUtils.asBytes(tmp); final byte[] dataByte = UuidUtils.asBytes(tmp);
ps.setBytes(iii.value, dataByte); ps.setBytes(iii.value, dataByte);
} else if (value instanceof final Long tmp) { } else if (value instanceof final Long tmp) {
this.LOGGER.debug("Inject Long => {}", tmp); LOGGER.debug("Inject Long => {}", tmp);
ps.setLong(iii.value, tmp); ps.setLong(iii.value, tmp);
} else if (value instanceof final Integer tmp) { } else if (value instanceof final Integer tmp) {
this.LOGGER.debug("Inject Integer => {}", tmp); LOGGER.debug("Inject Integer => {}", tmp);
ps.setInt(iii.value, tmp); ps.setInt(iii.value, tmp);
} else if (value instanceof final String tmp) { } else if (value instanceof final String tmp) {
this.LOGGER.debug("Inject String => {}", tmp); LOGGER.debug("Inject String => {}", tmp);
ps.setString(iii.value, tmp); ps.setString(iii.value, tmp);
} else if (value instanceof final Short tmp) { } else if (value instanceof final Short tmp) {
this.LOGGER.debug("Inject Short => {}", tmp); LOGGER.debug("Inject Short => {}", tmp);
ps.setShort(iii.value, tmp); ps.setShort(iii.value, tmp);
} else if (value instanceof final Byte tmp) { } else if (value instanceof final Byte tmp) {
this.LOGGER.debug("Inject Byte => {}", tmp); LOGGER.debug("Inject Byte => {}", tmp);
ps.setByte(iii.value, tmp); ps.setByte(iii.value, tmp);
} else if (value instanceof final Float tmp) { } else if (value instanceof final Float tmp) {
this.LOGGER.debug("Inject Float => {}", tmp); LOGGER.debug("Inject Float => {}", tmp);
ps.setFloat(iii.value, tmp); ps.setFloat(iii.value, tmp);
} else if (value instanceof final Double tmp) { } else if (value instanceof final Double tmp) {
this.LOGGER.debug("Inject Double => {}", tmp); LOGGER.debug("Inject Double => {}", tmp);
ps.setDouble(iii.value, tmp); ps.setDouble(iii.value, tmp);
} else if (value instanceof final Boolean tmp) { } else if (value instanceof final Boolean tmp) {
this.LOGGER.debug("Inject Boolean => {}", tmp); LOGGER.debug("Inject Boolean => {}", tmp);
ps.setBoolean(iii.value, tmp); ps.setBoolean(iii.value, tmp);
} else if (value instanceof final Timestamp tmp) { } else if (value instanceof final Timestamp tmp) {
this.LOGGER.debug("Inject Timestamp => {}", tmp); LOGGER.debug("Inject Timestamp => {}", tmp);
ps.setTimestamp(iii.value, tmp); ps.setTimestamp(iii.value, tmp);
} else if (value instanceof final Date tmp) { } else if (value instanceof final Date tmp) {
this.LOGGER.debug("Inject Date => {}", tmp); LOGGER.debug("Inject Date => {}", tmp);
ps.setTimestamp(iii.value, java.sql.Timestamp.from((tmp).toInstant())); ps.setTimestamp(iii.value, java.sql.Timestamp.from((tmp).toInstant()));
} else if (value instanceof final LocalDate tmp) { } else if (value instanceof final LocalDate tmp) {
this.LOGGER.debug("Inject LocalDate => {}", tmp); LOGGER.debug("Inject LocalDate => {}", tmp);
ps.setDate(iii.value, java.sql.Date.valueOf(tmp)); ps.setDate(iii.value, java.sql.Date.valueOf(tmp));
} else if (value instanceof final LocalTime tmp) { } else if (value instanceof final LocalTime tmp) {
this.LOGGER.debug("Inject LocalTime => {}", tmp); LOGGER.debug("Inject LocalTime => {}", tmp);
ps.setTime(iii.value, java.sql.Time.valueOf(tmp)); ps.setTime(iii.value, java.sql.Time.valueOf(tmp));
} else if (value.getClass().isEnum()) { } else if (value.getClass().isEnum()) {
this.LOGGER.debug("Inject ENUM => {}", value.toString()); LOGGER.debug("Inject ENUM => {}", value.toString());
ps.setString(iii.value, value.toString()); ps.setString(iii.value, value.toString());
} else { } else {
throw new DataAccessException("Not manage type ==> need to add it ..."); throw new DataAccessException("Not manage type ==> need to add it ...");

View File

@ -44,6 +44,7 @@ import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.FindOneAndUpdateOptions; import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.ReturnDocument; import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.InsertOneResult; import com.mongodb.client.result.InsertOneResult;
@ -304,8 +305,12 @@ public class DataAccessMorphia extends DataAccess {
} }
public <T> void setValueFromDoc(final Class<?> type, final Object data, final Field field, final Document doc) public <T> void setValueFromDoc(
throws Exception { final Class<?> type,
final Object data,
final Field field,
final Document doc,
final List<LazyGetter> lazyCall) throws Exception {
final String fieldName = AnnotationTools.getFieldName(field); final String fieldName = AnnotationTools.getFieldName(field);
if (!doc.containsKey(fieldName)) { if (!doc.containsKey(fieldName)) {
field.set(data, null); field.set(data, null);
@ -374,7 +379,11 @@ public class DataAccessMorphia extends DataAccess {
final String value = doc.getString(fieldName); final String value = doc.getString(fieldName);
field.set(data, value); field.set(data, value);
return; return;
}
if (type == UUID.class) {
final Object value = doc.get(fieldName, field.getType());
field.set(data, value);
return;
} }
if (type.isEnum()) { if (type.isEnum()) {
final String value = doc.getString(fieldName); final String value = doc.getString(fieldName);
@ -392,8 +401,15 @@ public class DataAccessMorphia extends DataAccess {
} }
return; return;
} }
final Object value = doc.get(fieldName, field.getType()); if (List.class == field.getType()) {
field.set(data, value); final Object value = doc.get(fieldName, field.getType());
field.set(data, value);
} else {
final Object value = createObjectFromDocument(doc.get(fieldName, Document.class), field.getType(), null,
lazyCall);
field.set(data, value);
}
return; return;
//throw new ArchiveException("wrong type of field [" + fieldName + "]: " + doc.toJson()); //throw new ArchiveException("wrong type of field [" + fieldName + "]: " + doc.toJson());
} }
@ -612,6 +628,51 @@ public class DataAccessMorphia extends DataAccess {
} }
protected Object convertDefaultField(String data, final Field field) throws Exception {
if (data.startsWith("'") && data.endsWith("'")) {
data = data.substring(1, data.length() - 1);
}
final Class<?> type = field.getType();
if (type == UUID.class) {
}
if (type == Long.class || type == long.class) {
return Long.parseLong(data);
}
if (type == Integer.class || type == int.class) {
return Integer.parseInt(data);
}
if (type == Float.class || type == float.class) {
return Float.parseFloat(data);
}
if (type == Double.class || type == double.class) {
return Double.parseDouble(data);
}
if (type == Boolean.class || type == boolean.class) {
return Boolean.parseBoolean(data);
}
if (type == Timestamp.class) {}
if (type == Date.class) {}
if (type == Instant.class) {}
if (type == LocalDate.class) {}
if (type == LocalTime.class) {}
if (type == String.class) {}
if (type.isEnum()) {
final boolean find = false;
final Object[] arr = type.getEnumConstants();
for (final Object elem : arr) {
if (elem.toString().equals(data)) {
return elem;
}
}
if (!find) {
throw new DataAccessException("Enum value does not exist in the Model: '" + data + "'");
}
}
LOGGER.warn("Request default of unknow native type {} => {}", type.getCanonicalName(), data);
return null;
}
public boolean isAddOnField(final Field field) { public boolean isAddOnField(final Field field) {
return findAddOnforField(field) != null; return findAddOnforField(field) != null;
} }
@ -678,7 +739,7 @@ public class DataAccessMorphia extends DataAccess {
continue; continue;
} }
final String tableFieldName = AnnotationTools.getFieldName(field); final String tableFieldName = AnnotationTools.getFieldName(field);
final Object currentInsertValue = field.get(data); Object currentInsertValue = field.get(data);
if (AnnotationTools.isPrimaryKey(field)) { if (AnnotationTools.isPrimaryKey(field)) {
primaryKeyField = field; primaryKeyField = field;
if (primaryKeyField.getType() == UUID.class) { if (primaryKeyField.getType() == UUID.class) {
@ -714,11 +775,17 @@ public class DataAccessMorphia extends DataAccess {
doc.append(tableFieldName, Date.from(Instant.now())); doc.append(tableFieldName, Date.from(Instant.now()));
continue; continue;
} }
if (!field.getClass().isPrimitive()) { if (currentInsertValue == null && !field.getClass().isPrimitive()) {
if (currentInsertValue == null) { final DefaultValue[] defaultValue = field.getDeclaredAnnotationsByType(DefaultValue.class);
final DefaultValue[] defaultValue = field.getDeclaredAnnotationsByType(DefaultValue.class); LOGGER.error("TODO: convert default value in the correct value for the DB...");
LOGGER.error("TODO: convert default value in the correct value for the DB..."); if (defaultValue.length == 0) {
continue; continue;
} else {
final String value = defaultValue[0].value();
if (value == null) {
continue;
}
currentInsertValue = convertDefaultField(value, field);
} }
} }
doc.append(tableFieldName, currentInsertValue); doc.append(tableFieldName, currentInsertValue);
@ -790,8 +857,14 @@ public class DataAccessMorphia extends DataAccess {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
continue; continue;
} }
final String name = AnnotationTools.getFieldName(field); final String fieldName = AnnotationTools.getFieldName(field);
if (!filterKey.getValues().contains(name)) { // update field is not conditioned by filter:
final boolean updateTime = field.getDeclaredAnnotationsByType(UpdateTimestamp.class).length != 0;
if (updateTime) {
docSet.append(fieldName, Date.from(Instant.now()));
continue;
}
if (!filterKey.getValues().contains(fieldName)) {
continue; continue;
} else if (AnnotationTools.isGenericField(field)) { } else if (AnnotationTools.isGenericField(field)) {
continue; continue;
@ -821,7 +894,7 @@ public class DataAccessMorphia extends DataAccess {
continue; continue;
} }
} }
setValuedb(type, data, field, name, docSet, docUnSet); setValuedb(type, data, field, fieldName, docSet, docUnSet);
} }
} }
@ -836,7 +909,7 @@ public class DataAccessMorphia extends DataAccess {
if (!docUnSet.isEmpty()) { if (!docUnSet.isEmpty()) {
actions.append("$unset", docUnSet); actions.append("$unset", docUnSet);
} }
LOGGER.info("update some values: {}", actions.toJson()); LOGGER.info("updateWhere with value: {}", actions.toJson());
final UpdateResult ret = collection.updateMany(filters, actions); final UpdateResult ret = collection.updateMany(filters, actions);
return ret.getModifiedCount(); return ret.getModifiedCount();
} catch (final SQLException ex) { } catch (final SQLException ex) {
@ -897,19 +970,10 @@ public class DataAccessMorphia extends DataAccess {
} }
} }
// This must be refactored to manage the .project of Morphia. public List<String> generateSelectField(final Class<?> clazz, final QueryOptions options) throws Exception {
public void generateSelectField(// // TODO: list of user select fields.
final StringBuilder querySelect, //
final StringBuilder query, //
final Class<?> clazz, //
final QueryOptions options, //
final CountInOut count//
) throws Exception {
/*
final boolean readAllfields = QueryOptions.readAllColomn(options); final boolean readAllfields = QueryOptions.readAllColomn(options);
final String collectionName = AnnotationTools.getCollectionName(clazz, options); final List<String> fieldsName = new ArrayList<>();
final String primaryKey = AnnotationTools.getPrimaryKeyField(clazz).getName();
boolean firstField = true;
for (final Field elem : clazz.getFields()) { for (final Field elem : clazz.getFields()) {
// static field is only for internal global declaration ==> remove it .. // static field is only for internal global declaration ==> remove it ..
@ -925,29 +989,9 @@ public class DataAccessMorphia extends DataAccess {
continue; continue;
} }
final String name = AnnotationTools.getFieldName(elem); final String name = AnnotationTools.getFieldName(elem);
if (firstField) { fieldsName.add(name);
firstField = false;
} else {
querySelect.append(",");
}
querySelect.append(" ");
if (addOn != null) {
LOGGER.error("TODO: Add on not managed .5. ");
//addOn.generateQuery(tableName, primaryKey, elem, querySelect, query, name, count, options);
} else {
querySelect.append(tableName);
querySelect.append(".");
querySelect.append(name);
count.inc();
}
} }
*/ return fieldsName;
}
@Override
public <T> List<T> getsWhere(final Class<T> clazz, final QueryOption... option) throws Exception {
final QueryOptions options = new QueryOptions(option);
return getsWhere(clazz, options);
} }
@Override @Override
@ -989,13 +1033,11 @@ public class DataAccessMorphia extends DataAccess {
final List<T> outs = new ArrayList<>(); final List<T> outs = new ArrayList<>();
final MongoCollection<Document> collection = this.db.getDatastore().getDatabase().getCollection(collectionName); final MongoCollection<Document> collection = this.db.getDatastore().getDatabase().getCollection(collectionName);
try { try {
// Select values to read
//generateSelectField(querySelect, query, clazz, options, count);
// Generate the filtering of the data: // Generate the filtering of the data:
final Bson filters = condition.getFilter(collectionName, options, deletedFieldName); final Bson filters = condition.getFilter(collectionName, options, deletedFieldName);
FindIterable<Document> retFind = null; FindIterable<Document> retFind = null;
if (filters != null) { if (filters != null) {
LOGGER.info("getsWhere Find filter: {}", filters.toBsonDocument().toJson()); //LOGGER.info("getsWhere Find filter: {}", filters.toBsonDocument().toJson());
retFind = collection.find(filters); retFind = collection.find(filters);
} else { } else {
retFind = collection.find(); retFind = collection.find();
@ -1021,12 +1063,17 @@ public class DataAccessMorphia extends DataAccess {
} else if (limits.size() > 1) { } else if (limits.size() > 1) {
throw new DataAccessException("Request with multiple 'limit'..."); throw new DataAccessException("Request with multiple 'limit'...");
} }
// Select values to read
final List<String> listFields = generateSelectField(clazz, options);
listFields.add("_id");
retFind = retFind.projection(Projections.include(listFields.toArray(new String[0])));
LOGGER.info("GetsWhere ...");
final MongoCursor<Document> cursor = retFind.iterator(); final MongoCursor<Document> cursor = retFind.iterator();
try (cursor) { try (cursor) {
while (cursor.hasNext()) { while (cursor.hasNext()) {
final Document doc = cursor.next(); final Document doc = cursor.next();
System.out.println(doc.toJson()); // Affichage du document en format JSON LOGGER.info(" - getWhere value: {}", doc.toJson());
final Object data = createObjectFromDocument(doc, clazz, options, lazyCall); final Object data = createObjectFromDocument(doc, clazz, options, lazyCall);
final T out = (T) data; final T out = (T) data;
outs.add(out); outs.add(out);
@ -1081,7 +1128,7 @@ public class DataAccessMorphia extends DataAccess {
LOGGER.error("TODO: Add on not managed .6. "); LOGGER.error("TODO: Add on not managed .6. ");
addOn.fillFromDoc(this, doc, elem, data, options, lazyCall); addOn.fillFromDoc(this, doc, elem, data, options, lazyCall);
} else { } else {
setValueFromDoc(elem.getType(), data, elem, doc); setValueFromDoc(elem.getType(), data, elem, doc, lazyCall);
} }
} }
return data; return data;
@ -1126,48 +1173,6 @@ public class DataAccessMorphia extends DataAccess {
return this.getWhere(clazz, options.getAllArray()); return this.getWhere(clazz, options.getAllArray());
} }
@Override
public <T> List<T> gets(final Class<T> clazz) throws Exception {
return getsWhere(clazz);
}
@Override
public <T> List<T> gets(final Class<T> clazz, final QueryOption... option) throws Exception {
return getsWhere(clazz, option);
}
/** Delete items with the specific Id (cf @Id) and some options. If the Entity is manage as a softDeleted model, then it is flag as removed (if not already done before).
* @param <ID_TYPE> Type of the reference @Id
* @param clazz Data model that might remove element
* @param id Unique Id of the model
* @param options (Optional) Options of the request
* @return Number of element that is removed. */
@Override
public <ID_TYPE> long delete(final Class<?> clazz, final ID_TYPE id, final QueryOption... options)
throws Exception {
final String hasDeletedFieldName = AnnotationTools.getDeletedFieldName(clazz);
if (hasDeletedFieldName != null) {
return deleteSoft(clazz, id, options);
} else {
return deleteHard(clazz, id, options);
}
}
/** Delete items with the specific condition and some options. If the Entity is manage as a softDeleted model, then it is flag as removed (if not already done before).
* @param clazz Data model that might remove element.
* @param condition Condition to remove elements.
* @param options (Optional) Options of the request.
* @return Number of element that is removed. */
@Override
public long deleteWhere(final Class<?> clazz, final QueryOption... option) throws Exception {
final String hasDeletedFieldName = AnnotationTools.getDeletedFieldName(clazz);
if (hasDeletedFieldName != null) {
return deleteSoftWhere(clazz, option);
} else {
return deleteHardWhere(clazz, option);
}
}
@Override @Override
public <ID_TYPE> long deleteHard(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) public <ID_TYPE> long deleteHard(final Class<?> clazz, final ID_TYPE id, final QueryOption... option)
throws Exception { throws Exception {

View File

@ -158,7 +158,7 @@ public class AddOnManyToOne implements DataAccessAddOn {
// local field to manage no remote object to retrieve. // local field to manage no remote object to retrieve.
if (field.getType() == Long.class || field.getType() == Integer.class || field.getType() == Short.class if (field.getType() == Long.class || field.getType() == Integer.class || field.getType() == Short.class
|| field.getType() == String.class || field.getType() == UUID.class) { || field.getType() == String.class || field.getType() == UUID.class) {
ioDb.setValueFromDoc(field.getType(), data, field, doc); ioDb.setValueFromDoc(field.getType(), data, field, doc, lazyCall);
return; return;
} }
final Class<?> objectClass = field.getType(); final Class<?> objectClass = field.getType();

View File

@ -77,7 +77,7 @@ public class Condition extends QueryOption {
} }
final List<Bson> filter = new ArrayList<>(); final List<Bson> filter = new ArrayList<>();
if (exclude_deleted && deletedFieldName != null) { if (exclude_deleted && deletedFieldName != null) {
filter.add(Filters.ne(deletedFieldName, false)); filter.add(Filters.eq(deletedFieldName, false));
} }
// Check if we have a condition to generate // Check if we have a condition to generate
if (this.condition != null) { if (this.condition != null) {

View File

@ -12,10 +12,12 @@ public class DBEntry implements Closeable {
final static Logger LOGGER = LoggerFactory.getLogger(DBEntry.class); final static Logger LOGGER = LoggerFactory.getLogger(DBEntry.class);
private final DBConfig config; private final DBConfig config;
private DbInterface ioDb; private DbInterface ioDb;
private Class<?> classes[] = {};
private static List<DBEntry> stored = new ArrayList<>(); private static List<DBEntry> stored = new ArrayList<>();
private DBEntry(final DBConfig config, final boolean root, final Class<?>... classes) throws IOException { private DBEntry(final DBConfig config, final boolean root, final Class<?>... classes) throws IOException {
this.config = config; this.config = config;
this.classes = classes;
if (root) { if (root) {
connectRoot(); connectRoot();
} else { } else {
@ -23,11 +25,12 @@ public class DBEntry implements Closeable {
} }
} }
public static DBEntry createInterface(final DBConfig config) throws IOException { public static DBEntry createInterface(final DBConfig config, final Class<?>... classes) throws IOException {
return createInterface(config, false); return createInterface(config, false, classes);
} }
public static DBEntry createInterface(final DBConfig config, final boolean root) throws IOException { public static DBEntry createInterface(final DBConfig config, final boolean root, final Class<?>... classes)
throws IOException {
if (config.getKeepConnected()) { if (config.getKeepConnected()) {
for (final DBEntry elem : stored) { for (final DBEntry elem : stored) {
if (elem == null) { if (elem == null) {
@ -41,7 +44,7 @@ public class DBEntry implements Closeable {
stored.add(tmp); stored.add(tmp);
return tmp; return tmp;
} else { } else {
return new DBEntry(config, root); return new DBEntry(config, root, classes);
} }
} }
@ -52,7 +55,7 @@ public class DBEntry implements Closeable {
} else if ("sqlite".equals(this.config.getType())) { } else if ("sqlite".equals(this.config.getType())) {
this.ioDb = new DbInterfaceSQL(this.config); this.ioDb = new DbInterfaceSQL(this.config);
} else if ("mongo".equals(this.config.getType())) { } else if ("mongo".equals(this.config.getType())) {
this.ioDb = new DbInterfaceMorphia(this.config); this.ioDb = new DbInterfaceMorphia(this.config, this.classes);
} else { } else {
throw new IOException("DB type: '" + this.config.getType() + "'is not managed"); throw new IOException("DB type: '" + this.config.getType() + "'is not managed");
} }
@ -64,7 +67,7 @@ public class DBEntry implements Closeable {
} else if ("sqlite".equals(this.config.getType())) { } else if ("sqlite".equals(this.config.getType())) {
this.ioDb = new DbInterfaceSQL(this.config); this.ioDb = new DbInterfaceSQL(this.config);
} else if ("mongo".equals(this.config.getType())) { } else if ("mongo".equals(this.config.getType())) {
this.ioDb = new DbInterfaceMorphia(this.config); this.ioDb = new DbInterfaceMorphia(this.config, this.classes);
} else { } else {
throw new IOException("DB type: '" + this.config.getType() + "'is not managed"); throw new IOException("DB type: '" + this.config.getType() + "'is not managed");
} }

View File

@ -1,6 +1,7 @@
package test.kar.archidata; package test.kar.archidata;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import org.kar.archidata.GlobalConfiguration; import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.dataAccess.DataAccess; import org.kar.archidata.dataAccess.DataAccess;
@ -9,6 +10,29 @@ import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import test.kar.archidata.dataAccess.model.SerializeAsJson;
import test.kar.archidata.dataAccess.model.SerializeListAsJson;
import test.kar.archidata.dataAccess.model.SimpleTable;
import test.kar.archidata.dataAccess.model.SimpleTableSoftDelete;
import test.kar.archidata.dataAccess.model.TypeManyToManyRemote;
import test.kar.archidata.dataAccess.model.TypeManyToManyRoot;
import test.kar.archidata.dataAccess.model.TypeManyToManyRootExpand;
import test.kar.archidata.dataAccess.model.TypeManyToOneRemote;
import test.kar.archidata.dataAccess.model.TypeManyToOneRoot;
import test.kar.archidata.dataAccess.model.TypeManyToOneRootExpand;
import test.kar.archidata.dataAccess.model.TypeManyToOneUUIDRemote;
import test.kar.archidata.dataAccess.model.TypeManyToOneUUIDRoot;
import test.kar.archidata.dataAccess.model.TypeManyToOneUUIDRootExpand;
import test.kar.archidata.dataAccess.model.TypeOneToManyRemote;
import test.kar.archidata.dataAccess.model.TypeOneToManyRoot;
import test.kar.archidata.dataAccess.model.TypeOneToManyRootExpand;
import test.kar.archidata.dataAccess.model.TypeOneToManyUUIDRemote;
import test.kar.archidata.dataAccess.model.TypeOneToManyUUIDRoot;
import test.kar.archidata.dataAccess.model.TypeOneToManyUUIDRootExpand;
import test.kar.archidata.dataAccess.model.TypesEnum1;
import test.kar.archidata.dataAccess.model.TypesEnum2;
import test.kar.archidata.dataAccess.model.TypesTable;
public class ConfigureDb { public class ConfigureDb {
final static private Logger LOGGER = LoggerFactory.getLogger(ConfigureDb.class); final static private Logger LOGGER = LoggerFactory.getLogger(ConfigureDb.class);
final static private String modeTestForced = "MONGO"; final static private String modeTestForced = "MONGO";
@ -24,6 +48,29 @@ public class ConfigureDb {
if (modeTestForced != null) { if (modeTestForced != null) {
modeTest = modeTestForced; modeTest = modeTestForced;
} }
final List<Class<?>> listObject = List.of( //
SerializeAsJson.class, //
SerializeListAsJson.class, //
SimpleTable.class, //
SimpleTableSoftDelete.class, //
TypeManyToManyRemote.class, //
TypeManyToManyRoot.class, //
TypeManyToManyRootExpand.class, //
TypeManyToOneRemote.class, //
TypeManyToOneRoot.class, //
TypeManyToOneRootExpand.class, //
TypeManyToOneUUIDRemote.class, //
TypeManyToOneUUIDRoot.class, //
TypeManyToOneUUIDRootExpand.class, //
TypeOneToManyRemote.class, //
TypeOneToManyRoot.class, //
TypeOneToManyRootExpand.class, //
TypeOneToManyUUIDRemote.class, //
TypeOneToManyUUIDRoot.class, //
TypeOneToManyUUIDRootExpand.class, //
TypesEnum1.class, //
TypesEnum2.class, //
TypesTable.class);
if ("SQLITE-MEMORY".equalsIgnoreCase(modeTest)) { if ("SQLITE-MEMORY".equalsIgnoreCase(modeTest)) {
ConfigBaseVariable.dbType = "sqlite"; ConfigBaseVariable.dbType = "sqlite";
ConfigBaseVariable.bdDatabase = null; ConfigBaseVariable.bdDatabase = null;
@ -50,7 +97,8 @@ public class ConfigureDb {
ConfigBaseVariable.dbUser = "root"; ConfigBaseVariable.dbUser = "root";
} }
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.getDbconfig()); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.getDbconfig(),
listObject.toArray(new Class<?>[0]));
entry.connect(); entry.connect();
removeDB(); removeDB();

View File

@ -45,7 +45,7 @@ public class TestJson {
@Order(1) @Order(1)
@Test @Test
public void testTableInsertAndRetrieve() throws Exception { public void testTableFactory() throws Exception {
final List<String> sqlCommand = DataFactory.createTable(SerializeAsJson.class); final List<String> sqlCommand = DataFactory.createTable(SerializeAsJson.class);
if (this.da instanceof final DataAccessSQL daSQL) { if (this.da instanceof final DataAccessSQL daSQL) {
for (final String elem : sqlCommand) { for (final String elem : sqlCommand) {

View File

@ -102,9 +102,12 @@ public class TestManyToOne {
Assertions.assertEquals(insertedRemote2.data, retrieve2.remote.data); Assertions.assertEquals(insertedRemote2.data, retrieve2.remote.data);
// remove values: // remove values:
final long count = this.da.delete(TypeManyToOneRemote.class, remote.id); try {
Assertions.assertEquals(1L, count); final long count = this.da.delete(TypeManyToOneRemote.class, insertedRemote2.id);
Assertions.assertEquals(1L, count);
} catch (final Exception ex) {
ex.printStackTrace();
}
// check fail: // check fail:
retrieve = this.da.get(TypeManyToOneRoot.class, insertedData.id); retrieve = this.da.get(TypeManyToOneRoot.class, insertedData.id);
@ -161,7 +164,7 @@ public class TestManyToOne {
Assertions.assertEquals(insertedRemote2.data, retrieve2.remote.data); Assertions.assertEquals(insertedRemote2.data, retrieve2.remote.data);
// remove values: // remove values:
final long count = this.da.delete(TypeManyToOneUUIDRemote.class, remote.uuid); final long count = this.da.delete(TypeManyToOneUUIDRemote.class, insertedRemote2.uuid);
Assertions.assertEquals(1, count); Assertions.assertEquals(1, count);
// check fail: // check fail:

View File

@ -93,7 +93,6 @@ public class TestSimpleTableSoftDelete {
// check the full values // check the full values
final SimpleTableSoftDelete retrieve = this.da.get(SimpleTableSoftDelete.class, final SimpleTableSoftDelete retrieve = this.da.get(SimpleTableSoftDelete.class,
TestSimpleTableSoftDelete.idOfTheObject, QueryOptions.READ_ALL_COLOMN); TestSimpleTableSoftDelete.idOfTheObject, QueryOptions.READ_ALL_COLOMN);
Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id); Assertions.assertNotNull(retrieve.id);
Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id); Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id);

View File

@ -3,6 +3,9 @@ package test.kar.archidata.dataAccess.model;
import org.kar.archidata.annotation.DataJson; import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.model.GenericData; import org.kar.archidata.model.GenericData;
import dev.morphia.annotations.Entity;
@Entity
public class SerializeAsJson extends GenericData { public class SerializeAsJson extends GenericData {
@DataJson @DataJson

View File

@ -5,6 +5,9 @@ import java.util.List;
import org.kar.archidata.annotation.DataJson; import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.model.GenericData; import org.kar.archidata.model.GenericData;
import dev.morphia.annotations.Entity;
@Entity
public class SerializeListAsJson extends GenericData { public class SerializeListAsJson extends GenericData {
@DataJson @DataJson

View File

@ -2,6 +2,9 @@ package test.kar.archidata.dataAccess.model;
import org.kar.archidata.model.GenericData; import org.kar.archidata.model.GenericData;
import dev.morphia.annotations.Entity;
@Entity
public class SimpleTable extends GenericData { public class SimpleTable extends GenericData {
public String data; public String data;

View File

@ -2,6 +2,9 @@ package test.kar.archidata.dataAccess.model;
import org.kar.archidata.model.GenericDataSoftDelete; import org.kar.archidata.model.GenericDataSoftDelete;
import dev.morphia.annotations.Entity;
@Entity
public class SimpleTableSoftDelete extends GenericDataSoftDelete { public class SimpleTableSoftDelete extends GenericDataSoftDelete {
public String data; public String data;
} }

View File

@ -4,9 +4,11 @@ import java.util.List;
import org.kar.archidata.model.GenericData; import org.kar.archidata.model.GenericData;
import dev.morphia.annotations.Entity;
import jakarta.persistence.FetchType; import jakarta.persistence.FetchType;
import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToMany;
@Entity
public class TypeManyToManyRemote extends GenericData { public class TypeManyToManyRemote extends GenericData {
@ManyToMany(fetch = FetchType.LAZY, targetEntity = TypeManyToManyRoot.class, mappedBy = "remote") @ManyToMany(fetch = FetchType.LAZY, targetEntity = TypeManyToManyRoot.class, mappedBy = "remote")
public List<Long> remoteToParent; public List<Long> remoteToParent;

View File

@ -4,9 +4,11 @@ import java.util.List;
import org.kar.archidata.model.GenericData; import org.kar.archidata.model.GenericData;
import dev.morphia.annotations.Entity;
import jakarta.persistence.FetchType; import jakarta.persistence.FetchType;
import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToMany;
@Entity
public class TypeManyToManyRoot extends GenericData { public class TypeManyToManyRoot extends GenericData {
public String otherData; public String otherData;

View File

@ -2,6 +2,9 @@ package test.kar.archidata.dataAccess.model;
import org.kar.archidata.model.GenericData; import org.kar.archidata.model.GenericData;
import dev.morphia.annotations.Entity;
@Entity
public class TypeManyToOneRemote extends GenericData { public class TypeManyToOneRemote extends GenericData {
public String data; public String data;

View File

@ -2,9 +2,11 @@ package test.kar.archidata.dataAccess.model;
import org.kar.archidata.model.GenericData; import org.kar.archidata.model.GenericData;
import dev.morphia.annotations.Entity;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.ManyToOne; import jakarta.persistence.ManyToOne;
@Entity
public class TypeManyToOneRoot extends GenericData { public class TypeManyToOneRoot extends GenericData {
public String otherData; public String otherData;

View File

@ -2,6 +2,9 @@ package test.kar.archidata.dataAccess.model;
import org.kar.archidata.model.UUIDGenericData; import org.kar.archidata.model.UUIDGenericData;
import dev.morphia.annotations.Entity;
@Entity
public class TypeManyToOneUUIDRemote extends UUIDGenericData { public class TypeManyToOneUUIDRemote extends UUIDGenericData {
public String data; public String data;

View File

@ -4,9 +4,11 @@ import java.util.UUID;
import org.kar.archidata.model.UUIDGenericData; import org.kar.archidata.model.UUIDGenericData;
import dev.morphia.annotations.Entity;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.ManyToOne; import jakarta.persistence.ManyToOne;
@Entity
public class TypeManyToOneUUIDRoot extends UUIDGenericData { public class TypeManyToOneUUIDRoot extends UUIDGenericData {
public String otherData; public String otherData;

View File

@ -2,9 +2,11 @@ package test.kar.archidata.dataAccess.model;
import org.kar.archidata.model.GenericData; import org.kar.archidata.model.GenericData;
import dev.morphia.annotations.Entity;
import jakarta.persistence.FetchType; import jakarta.persistence.FetchType;
import jakarta.persistence.ManyToOne; import jakarta.persistence.ManyToOne;
@Entity
public class TypeOneToManyRemote extends GenericData { public class TypeOneToManyRemote extends GenericData {
@ManyToOne(fetch = FetchType.LAZY, targetEntity = TypeOneToManyRoot.class) @ManyToOne(fetch = FetchType.LAZY, targetEntity = TypeOneToManyRoot.class)

View File

@ -4,8 +4,10 @@ import java.util.List;
import org.kar.archidata.model.GenericData; import org.kar.archidata.model.GenericData;
import dev.morphia.annotations.Entity;
import jakarta.persistence.OneToMany; import jakarta.persistence.OneToMany;
@Entity
public class TypeOneToManyRoot extends GenericData { public class TypeOneToManyRoot extends GenericData {
public String otherData; public String otherData;

View File

@ -4,9 +4,11 @@ import java.util.UUID;
import org.kar.archidata.model.UUIDGenericData; import org.kar.archidata.model.UUIDGenericData;
import dev.morphia.annotations.Entity;
import jakarta.persistence.FetchType; import jakarta.persistence.FetchType;
import jakarta.persistence.ManyToOne; import jakarta.persistence.ManyToOne;
@Entity
public class TypeOneToManyUUIDRemote extends UUIDGenericData { public class TypeOneToManyUUIDRemote extends UUIDGenericData {
@ManyToOne(fetch = FetchType.LAZY, targetEntity = TypeOneToManyUUIDRoot.class) @ManyToOne(fetch = FetchType.LAZY, targetEntity = TypeOneToManyUUIDRoot.class)

View File

@ -5,9 +5,11 @@ import java.util.UUID;
import org.kar.archidata.model.UUIDGenericData; import org.kar.archidata.model.UUIDGenericData;
import dev.morphia.annotations.Entity;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.OneToMany; import jakarta.persistence.OneToMany;
@Entity
public class TypeOneToManyUUIDRoot extends UUIDGenericData { public class TypeOneToManyUUIDRoot extends UUIDGenericData {
public String otherData; public String otherData;

View File

@ -1,10 +1,12 @@
package test.kar.archidata.dataAccess.model; package test.kar.archidata.dataAccess.model;
import dev.morphia.annotations.Entity;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType; import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
@Entity
public class TypesEnum1 { public class TypesEnum1 {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@ -1,10 +1,12 @@
package test.kar.archidata.dataAccess.model; package test.kar.archidata.dataAccess.model;
import dev.morphia.annotations.Entity;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType; import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
@Entity
public class TypesEnum2 { public class TypesEnum2 {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@ -5,11 +5,13 @@ import java.time.LocalDate;
import java.time.LocalTime; import java.time.LocalTime;
import java.util.Date; import java.util.Date;
import dev.morphia.annotations.Entity;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType; import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
@Entity
public class TypesTable { public class TypesTable {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)