熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

動態表單及動態建表實現原理

2013-11-23 18:41:53  來源: Java核心技術 

  應用場景

  項目中往往需要動態的創建一個表單或者添加一個新的數據模板這時候因為需要在運行時動態的創建表以及動態的維護表字段甚至表關系 使得普通java解決方案變得困難重重

  實現工具

  Hibernate + Spring + Groovy +Freemarker

  Hibernate 作用很簡單負責創建數據庫表這樣可以避免我們自己去寫復雜的sql和判斷

  Spring 作為橋梁起到連接紐帶的作用

  Groovy做為動態語言在項目運行時根據模板創建訪問數據庫或者控制層代碼

  Freamker 可以根據提前定義好的模板生成 hibernate配置文件以及Groovy代碼

  實現原理

  首先創建Form 和 FromAttribute 兩張表關系一對多Form表記錄表單的名稱類別甚至是作為在動態生成表單時的css樣式信息FromAttribute記錄表單字段信息如名稱類別等有了表單以及表單項的信息後就可以創建數據庫表了

  測試代碼

  public void testGenerator(){

  Form form = formServicegetAll()get(

  List list = formAttributeService

  getAttributeListByFormId(formgetId())formsetFormAttributeList(list)DbGenerator dg = new DbGenerator(form dataSource)dggenerator()

  }

  DbGenerator

  import javaioIOExceptionimport javaioStringWriterimport javaioWriterimport javasqlSQLExceptionimport javautilHashMapimport javautilMapimport javautilProperties

  import javaxsqlDataSource

  import orghibernatetoolhbmddlSchemaExportimport orgslfjLoggerimport orgslfjLoggerFactory

  import freemarkertemplateConfigurationimport freemarkertemplateTemplateimport freemarkertemplateTemplateException

  public class DbGenerator {

  private DataSource dataSource

  protected Map root = new HashMap()

  private static Logger log = LoggerFactorygetLogger(FormGeneratorclass)

  protected String path

  protected String packageName

  private Form form

  protected Configuration getConfig(String resource){

  Configuration cfg = new Configuration()

  cfgsetDefaultEncoding(UTFcfgsetClassForTemplateLoading(thisgetClass() resource)

  return cfg

  }

  public DbGenerator(Form form DataSource dataSource) { thisform = formthisdataSource = dataSource

  }

  public void generator(){

  if(null == formgetFormAttributeList() || formgetFormAttributeList()size() == ){

  return

  }

  Template t

  try {

  t = getConfig(/templategetTemplate(hibernateftl

  Writer out = new StringWriter()

  tprocess(getMapContext() out)String xml = outtoString()

  createTable(xml)

  logdebug(xml)

  } catch(IOException e){

  eprintStackTrace()

  } catch(TemplateException e){

  eprintStackTrace()

  }

  @SuppressWarnings(unchecked

  Map getMapContext(){

  rootput(entity form)

  return root

  }

  public void createTable(String xml){

  orghibernatecfgConfiguration conf = new orghibernatecfgConfiguration()nfigure(/hibernate/hibernatecfgxml

  Properties extraProperties = new Properties()

  extraPropertiesput(hibernatehbmddlauto createconfaddProperties(extraProperties)

  confaddXML(xml)

  SchemaExport dbExport

  try {

  dbExport = new SchemaExport(conf dataSourcegetConnection())// dbExportsetOutputFile(path)dbExportcreate(false true)

  } catch(SQLException e){

  // TODO Autogenerated catch block

  eprintStackTrace()

  }

  }

  class hibernateGenerator {

  }hibernateftl

  hibernatecfgxml

  orghibernatedialectSQLServerDialect

  netsourceforgejtdsjdbcDriver

  jdbcjtdssqlserver://databasename=strutsSelectMethod=cursor

  sa

  sa

  true

  update

  ——>

  創建好數據庫後就要利用groovy動態創建訪問代碼了先看測試代碼再看具體實現

  public void testGroovy(){

  Form form = formServiceget(

  List list = formAttributeService

  getAttributeListByFormId(formgetId())formsetFormAttributeList(list)

  FormGenerator fg = new FormGenerator(form)

  String groovycode = fggenerator()ClassLoader parent = getClass()getClassLoader()

  GroovyClassLoader loader = new GroovyClassLoader(parent)

  Class groovyClass = loaderparseClass(groovycode)

  GroovyObject groovyObject = null

  try {

  groovyObject = (GroovyObject) groovyClassnewInstance()

  } catch(InstantiationException e){

  eprintStackTrace()

  } catch(IllegalAccessException e){

  eprintStackTrace()

  }

  // map中key為formAttribute中描述該表單字段在數據庫中的名稱c_columnName

  //具體情況根據formAttribute而定

  Map map = new HashMap()

  mapput(name limq

  //調用insert方法插入數據

  int c = (Integer) groovyObjectinvokeMethod(insert map)

  //調用getAll方法獲得所有動態表中的數據

  Object o = groovyObjectinvokeMethod(getAll null)

  List list =(List)o

  Object obj = listget(

  try {

  String tname = (String) BeanUtilsgetDeclaredProperty(obj nameSystemoutprintln(tname)

  } catch(IllegalAccessException e){

  eprintStackTrace()

  } catch(NoSuchFieldException e){

  eprintStackTrace()

  }

  //調用search方法查詢動態表

  List returnList = (List) groovyObjectinvokeMethod(search map)

  for(Map mapreturnList){

  //同理此處根據FromAttribute而定

  Systemoutprintln(mapget(id))Systemoutprintln(mapget(name))Systemoutprintln(mapget(type))

  }

  }FormGenerator創建訪問數據庫Groovy代碼

  public class FormGenerator {

  protected Map root = new HashMap()

  private static Logger log = LoggerFactorygetLogger(FormGeneratorclass)

  protected String path

  protected String packageName

  private Form form

  protected Configuration getConfig(String resource){

  Configuration cfg = new Configuration()

  cfgsetDefaultEncoding(UTFcfgsetClassForTemplateLoading(thisgetClass() resource)

  return cfg

  }

  public FormGenerator(Form form){

  thisform = form

  }

  public String generator(){

  String returnstr = null

  Template t

  try {

  t = getConfig(/templategetTemplate(FormServiceftl//Writer out = new OutputStreamWriter(new FileOutputStream(new File(path))UTF

  Writer out = new StringWriter()

  tprocess(getMapContext() out)returnstr = outtoString()logdebug(returnstr)

  } catch(IOException e){

  eprintStackTrace()

  } catch(TemplateException e){

  eprintStackTrace()

  }

  return returnstr

  }

  @SuppressWarnings(unchecked

  Map getMapContext(){

  rootput(entity form)rootput(insert SqlHelperbuildInsertStatement(form))rootput(update SqlHelperbuildUpdateStatement(form))

  rootput(insertParameter SqlHelperbuildInsertparameter(form))rootput(updateParameter SqlHelperbuildUpdateparameter(form))

  rootput(delete SqlHelperbuildDeleteStatement(form))rootput(query  SqlHelperbuildQueryStatement(form))

  return root

  }

  }FormServiceftl import javasqlResultSet import javasqlSQLException import javasqlTypes import orgsprireRowMapper import orgsprireRowMapperResultSetExtractor import redaoDataSourceFactory import monslangbuilderToStringBuilderimport monslangbuilderToStringStyle

  class ${entityname?cap_first}Dao {

  def insert = ${insert}

  def delete = ${delete}

  def update = ${update}

  def int insert(entity){

  def Object[] params = [${insertParameter}]

  def int[] types=[TypesVARCHAR] return DataSourceFactorygetJdbcTemplate()update(insert params types)

  }

  def int update(entity){

  def Object[] params = [${updateParameter}]

  return DataSourceFactorygetJdbcTemplate()update(update params)

  }

  def int delete(String entityId){

  def Object[] params =[entityId]

  return DataSourceFactorygetJdbcTemplate()update(delete params)

  }

  def search(entity){

  ${query}

  println(query)

  return DataSourceFactorygetJdbcTemplate()queryForList(query)

  }

  }

  以上代碼示意了如何利用 freemarker 生成 Groovy 和 hibernate 相關代碼以及如何利用Groovy動態的對數據庫進行創建和增刪改查操作了解以上的原理後就可以方便的在運行時利用freemarker生成表示層頁面以及代碼來進行展示


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25599.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.