Wie @Machado sagte, ist der einfachste Weg, dies zu vermeiden und die gesamte Verarbeitung in Ihrem Haupt-Java durchzuführen. Es ist jedoch weiterhin möglich, die Codebasis mit ähnlichem Code zu codieren, ohne dass Sie sich selbst wiederholen müssen, indem Sie den Code für beide Codebasis generieren.
Verwenden Sie beispielsweise cog enable, um die drei Ausschnitte aus einer gemeinsamen Definition zu generieren
Snippet 1:
/*[[[cog
from generate import generate_sql_table
cog.outl(generate_sql_table("rectangle"))
]]]*/
CREATE TABLE rectangles (
width int,
height int
);
/*[[[end]]]*/
Snippet 2:
public class Rectangle {
/*[[[cog
from generate import generate_domain_attributes,generate_domain_logic
cog.outl(generate_domain_attributes("rectangle"))
cog.outl(generate_domain_logic("rectangle"))
]]]*/
private int width;
private int height;
public int area {
return width * heigh;
}
/*[[[end]]]*/
}
Snippet 3:
/*[[[cog
from generate import generate_sql
cog.outl(generate_sql("rectangle","""
SELECT sum({area})
FROM rectangles r"""))
]]]*/
SELECT sum((r.width * r.heigh))
FROM rectangles r
/*[[[end]]]*/
aus einer Referenzdatei
import textwrap
import pprint
# the common definition
types = {"rectangle":
{"sql_table_name": "rectangles",
"sql_alias": "r",
"attributes": [
["width", "int"],
["height", "int"],
],
"methods": [
["area","int","this.width * this.heigh"],
]
}
}
# the utilities functions
def generate_sql_table(name):
type = types[name]
attributes =",\n ".join("{attr_name} {attr_type}".format(
attr_name=attr_name,
attr_type=attr_type)
for (attr_name,attr_type)
in type["attributes"])
return """
CREATE TABLE {table_name} (
{attributes}
);""".format(
table_name=type["sql_table_name"],
attributes = attributes
).lstrip("\n")
def generate_method(method_def):
name,type,value =method_def
value = value.replace("this.","")
return textwrap.dedent("""
public %(type)s %(name)s {
return %(value)s;
}""".lstrip("\n"))% {"name":name,"type":type,"value":value}
def generate_sql_method(type,method_def):
name,_,value =method_def
value = value.replace("this.",type["sql_alias"]+".")
return name,"""(%(value)s)"""% {"value":value}
def generate_domain_logic(name):
type = types[name]
attributes ="\n".join(generate_method(method_def)
for method_def
in type["methods"])
return attributes
def generate_domain_attributes(name):
type = types[name]
attributes ="\n".join("private {attr_type} {attr_name};".format(
attr_name=attr_name,
attr_type=attr_type)
for (attr_name,attr_type)
in type["attributes"])
return attributes
def generate_sql(name,sql):
type = types[name]
fields ={name:value
for name,value in
(generate_sql_method(type,method_def)
for method_def in type["methods"])}
sql=textwrap.dedent(sql.lstrip("\n"))
print (sql)
return sql.format(**fields)