我有来自mysql的源数据类型和来自mongodb的目标数据类型。
如果源数据类型是varchar,我如何转换为字符串并使用convertToTargetDataType方法将该值设置为文档。任何人都可以帮我解决这个问题...
private Document prepareDoc(ResultSet rs, List<Columns> columns) throws SQLException {
Document document = new Document();
for (Columns col : columns) {
String sourceDataType = col.getSourceDataType();
String targetDataType = col.getTargetDataType();
String key = col.getColumnName();
String value = null;
switch (sourceDataType) {
case "varchar": {
//String value = rs.getString(key);
document.put(key, convertToTargetDataType(targetDataType, value));
break;
}
case "int": {
//double value = rs.getDouble(key);
document.put(key, convertToTargetDataType(targetDataType, value));
break;
}
case "date": {
//Date value = rs.getDate(key);
document.put(key, convertToTargetDataType(targetDataType, value));
break;
}
}
}
return document;
}
public Object convertToTargetDataType(String targetDataType, String value) {
//if target datatype = value datatype ,return that datatype
return null;
}
假设你打算使用MongoDB,值得注意的是,你不需要在插入之前使用的某种预定义类型。
由于您的对象是动态的,并且您事先不知道架构,因此您可以简单地将结果集中的对象追加到文档中:
private Document prepareDoc(ResultSet rs, List<Columns> columns) throws SQLException {
Document document = new Document();
for (Columns col : columns) {
String sourceDataType = col.getSourceDataType();
String targetDataType = col.getTargetDataType();
String key = col.getColumnName();
//The correct JSON type will be used based on the ACTUAL JAVA TYPE RETURNED BY THE DRIVER
document.put(key, rs.getObject(key));
}
return document;
}
注意:请务必检查驱动程序在 RS 中为您提供的各自 SQL 类型的具体类。行为可能会有所不同,因此请确保您的特定 RDBMS 的 JDBC 驱动程序为您提供了一些可用的东西(尤其是如果您使用狡猾的类型,例如 blob 等)。但总的来说,这应该适用于最常见的类型。