本人在开发过程中,需要在Dao文件里的resultMap中的collection里配置十几个字段的映射,而且都设置了columnPrefix,如果在sql语句中一个一个AS非常的机械!
因此写了个小应用,实现collection标签中的内容自动转换成了SQL字段AS的字符串,直接粘贴到sql语句中即可
代码如下:
from xml.etree import ElementTree as ET
def parse_xml(xml_string):
root = ET.fromstring(xml_string)
result = []
#根据需要更改collection还是association
for collection in root.findall(".//collection"):
#基本不需要修改
column_prefix = collection.get("columnPrefix", "")
id_element = collection.findall(".//id")
result.append(f"{prefix}.id AS {column_prefix}id")
for result_element in collection.findall(".//result"):
column = result_element.get("column")
result.append(f"{prefix}.{column} AS {column_prefix}{column}")
return ",\n".join(result)
xml_string = '''
<resultMap>
使用说明:所有内容粘贴在resultMap标签里!!!替换我们就好!
注意:只能识别一个collection,如果是嵌套collection,可以取巧的单独运行一次,并且将collection中的columnPrefix补全即可
例如:
源xml
<collection columnPrefix="task_">
...
<collection columnPrefix="step_">
...
</collection>
</collection>
步骤:
1、先将第一个collection复制到这里,运行
2、在将第二个collection复制替换第一个的内容,将columnPrefix更改为columnPrefix="task_step_".
同时别忘记更改下面的【prefix】变量哦!!
输出效果,例:
its.id AS task_step_id,
its.name AS task_step_name,
its.photo_record AS task_step_photo_record,
its.operation AS task_step_operation,
its.record_method AS task_step_record_method,
its.result AS task_step_result,
its.images AS task_step_images,
its.updated_at AS task_step_updated_at,
its.skipped AS task_step_skipped,
its.skipped_reason_id AS task_step_skipped_reason_id,
its.skipped_reason_name AS task_step_skipped_reason_name,
its.abnormal_content AS task_step_abnormal_content
</resultMap>
''' # 将上面的XML数据粘贴到这里
#这里需要手动的更改别名
prefix = "its"
print(parse_xml(xml_string))
希望能提高友友们的开发效率奥~
感谢阅读!