Comme l'a dit @Machado, la façon la plus simple de le faire est de l'éviter et de faire tout votre traitement dans votre java principal. Cependant, il est toujours possible d'avoir à coder la base avec un code similaire sans se répéter soi-même en générant le code pour les deux bases de code.
Par exemple, en utilisant cog enable pour générer les trois extraits à partir d'une définition commune
extrait 1:
/*[[[cog
from generate import generate_sql_table
cog.outl(generate_sql_table("rectangle"))
]]]*/
CREATE TABLE rectangles (
width int,
height int
);
/*[[[end]]]*/
extrait 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]]]*/
}
extrait 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]]]*/
à partir d'un fichier de référence
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)