首页 / 软件开发 / JAVA / 动态表单及动态建表实现原理
动态表单及动态建表实现原理2011-01-08 blogjava limq1 应用场景项目中往往需要动态的创建一个表单,或者添加一个新的数据模板,这时候因为需要在运行时动态的创建表以及动态的维护表字段甚至表关系 使得普通java解决方案变得困难重重。2 实现工具Hibernate + Spring + Groovy +FreemarkerHibernate 作用很简单负责创建数据库表这样可以避免我们自己去写复杂的sql和判断。Spring 作为桥梁起到连接纽带的作用。Groovy做为动态语言,在项目运行时根据模板创建访问数据库,或者控制层代码。Freamker 可以根据提前定义好的模板生成 hibernate配置文件,以及Groovy代码。3 实现原理首先创建Form 和 FromAttribute 两张表关系一对多。Form表记录表单的名称,类别,甚至是作为在动态生成表单时的css样式信息。FromAttribute记录表单字段信息,如名称,类别等。有了表单以及表单项的信息后就可以创建数据库表了。测试代码:public void testGenerator() { Form form = formService.getAll().get(0); List<FormAttribute> list = formAttributeService .getAttributeListByFormId(form.getId()); form.setFormAttributeList(list); DbGenerator dg = new DbGenerator(form, dataSource); dg.generator(); } DbGenerator import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class DbGenerator { private DataSource dataSource; protected Map root = new HashMap(); private static Logger log = LoggerFactory.getLogger(FormGenerator.class); protected String path; protected String packageName; private Form form; protected Configuration getConfig(String resource) { Configuration cfg = new Configuration(); cfg.setDefaultEncoding("UTF-8"); cfg.setClassForTemplateLoading(this.getClass(), resource); return cfg; } public DbGenerator(Form form ,DataSource dataSource) { this.form = form; this.dataSource = dataSource; } public void generator() { if(null == form.getFormAttributeList() || form.getFormAttributeList().size() == 0){ return ; } Template t; try { t = getConfig("/template").getTemplate("hibernate.ftl"); Writer out = new StringWriter(); t.process(getMapContext(), out); String xml = out.toString(); createTable(xml); log.debug(xml); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") Map getMapContext() { root.put("entity", form); return root; } public void createTable(String xml) { org.hibernate.cfg.Configuration conf = new org.hibernate.cfg.Configuration(); conf.configure("/hibernate/hibernate.cfg.xml"); Properties extraProperties = new Properties(); extraProperties.put("hibernate.hbm2ddl.auto", "create"); conf.addProperties(extraProperties); conf.addXML(xml); SchemaExport dbExport; try { dbExport = new SchemaExport(conf, dataSource.getConnection()); // dbExport.setOutputFile(path); dbExport.create(false, true); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class hibernateGenerator { }
收藏该网址