动态表单及动态建表实现原理
2009-09-22 00:00:00 来源:WEB开发网hibernate.cfg.xml
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="connection.url">jdbc:jtds:sqlserver://127.0.0.1:1433;databasename=struts;SelectMethod=cursor</property>
<property name="connection.username">sa</property>
<property name="connection.password">sa</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!--
<mapping resource="hibernate/FormAttribute.hbm.xml" />
<mapping resource="hibernate/Form.hbm.xml" />
-->
</session-factory>
</hibernate-configuration>
创建好数据库后 就要利用groovy动态创建访问代码了:先看测试代码 再看具体实现:
public void testGroovy() {
Form form = formService.get("1");
List<FormAttribute> list = formAttributeService
.getAttributeListByFormId(form.getId());
form.setFormAttributeList(list);
FormGenerator fg = new FormGenerator(form);
String groovycode = fg.generator();
ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass = loader.parseClass(groovycode);
GroovyObject groovyObject = null;
try {
groovyObject = (GroovyObject) groovyClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// map中key为formAttribute中描述该表单字段在数据库中的名称c_columnName
// 具体情况根据formAttribute而定
Map map = new HashMap();
map.put("name", "limq");
// 调用insert方法插入数据
int c = (Integer) groovyObject.invokeMethod("insert", map);
// 调用getAll方法获得所有动态表中的数据
Object o = groovyObject.invokeMethod("getAll", null);
List list2 = (List) o;
Object obj = list2.get(0);
try {
String tname = (String) BeanUtils.getDeclaredProperty(obj, "name");
System.out.println(tname);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
// 调用search方法查询动态表
List<Map> returnList = (List) groovyObject.invokeMethod("search", map);
for (Map map2 : returnList) {
// 同理此处根据FromAttribute而定
System.out.println(map2.get("id"));
System.out.println(map2.get("name"));
System.out.println(map2.get("type"));
}
}
更多精彩
赞助商链接