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

用Groovy實現最簡單的ORM

2013-11-23 18:57:22  來源: Java核心技術 
我參加的學校創新試驗項目就用它來實現最簡易的ORM做的非常簡單主要原因是沒有時間因為小弟學業繁重所以抽出一個下午的時間來實現一個簡易版的ORM數據庫用的是MySQL現在簡單說明一下所示代碼將User類的一個實例通過save方法保存到數據庫中然後再根據給定條件通過findBy方法從數據庫中取出實例最後刪除一個特定實例由於深知通過XML文件進行配置的痛苦所以在設計時沒有用到任何XML文件此程序讓程序員只需關注自己要處理的對象而不用關心數據庫方面的東西簡化開發過程最後我想說明的是由於時間問題所以編碼方面只注重算法的體現沒有考慮其他方面下面給出的代碼僅供演示及參考(源碼已經上傳點擊下載)

     package eduecustorm       import groovysqlSql    import groovytextTemplate    import groovytextSimpleTemplateEngine       public class User {    private int id    private String name    private int age       public User() {}       public User( int id) {    this id = id    }       public User( int id String name int age) {    thisid = id    thisname = name    thisage = age    }       public int getId() {    return id    }       public void setId( int id) {    thisid = id    }       public String getName() {    return name    }       public void setName(String name) {    thisname = name    }       public int getAge() {    return age    }       public void setAge( int age) {    thisage = age    }             public String toString() {    return name + (# + id + + age + )    }    }       typemap = [ int : INTEGER javalangInteger : INTEGER long : BIGINT
javalangLong : BIGINT short : SMALLINT javalangShort : SMALLINT
byte : TINYINT javalangByte : TINYINT float : FLOAT javalangFloat
: FLOAT double : DOUBLE javalangDouble : DOUBLE javamathBigDecimal
: NUMERIC char : CHAR() javalangCharacter : CHAR() javalangString
: VARCHAR() boolean : BIT javalangBoolean : BIT ]       def capitalize(str) {    def c = strcharAt( )    int asci = ( int )c    if (asci > && asci < ) {    return (( char )(asci ))toString() + strsubstring( )    }    }       def user = new User( Daniel )       def connect() {    return SqlnewInstance(    jdbc:mysql://localhost:/orm root    commysqljdbcDriver )    }       def pointToLine(str) {    return strreplaceAll( \\p{Punct} _ )    }       def getFields(u) {    def clazz = ugetClass()    def fields = clazzgetDeclaredFields()    def fieldunit = [:]    for (f in fields) {    def fstr = ftoString()    if (fstrstartsWith( private )) {    def fieldname = fstrsubstring(fstrlastIndexOf( ) + )    def methodname = get + capitalize(fieldname)    fieldunitput(fieldname clazzgetMethod(methodname)invoke(u))    }    }       return fieldunit    }       tablename = ;    def save(u) {    def clazz = ugetClass()    def classname = clazzgetName()    def classunit = [:]    fieldunit = getFields(u)    classunitput(classname fieldunit)    def keySet = classunitkeySet()    def it = erator()    def fields    while (ithasNext()) {    tablename = itnext()    fields = classunitget(tablename)    }    tablename = pointToLine(tablename)    def fkeySet = fieldskeySet()    def fit = erator()    def creationstmt =       def order = [:]    def num =    while (fithasNext()) {    def fieldname = fitnext()    def fieldvalue = fieldsget(fieldname)    if ( id == fieldname) {    creationstmt += id INTEGER PRIMARY KEY not null    } else {    creationstmt += fieldname + + typemapget(fieldvaluegetClass()getName()) +    }    orderput(num++ fieldname)    }    creationstmt = creationstmtsubstring( creationstmtlength() )    def valuestr = (    def vkeySet = orderkeySet()    def vit = erator()    params = (    while (vithasNext()) {    def elem = vitnext()    def v = orderget(elem)    valuestr += \${ + v + }    params += ` + v + `    }    valuestr = valuestrsubstring( valuestrlength() )    params = paramssubstring( paramslength() )    valuestr += )    params += )    def insertstmt = INSERT INTO ` + tablename + ` + params + VALUES    insertstmt += valuestr    def engine = new SimpleTemplateEngine()    def template = enginecreateTemplate(insertstmt)make(fields)    insertstmt = templatetoString()    def createstmt =    CREATE TABLE IF NOT EXISTS ` + tablename + `    (    + creationstmt +    );       try {    def sql = connect()    sqlexecute(createstmt)    sqlexecute(insertstmt)       } catch (Exception e) {    int id = ugetId()    id++    usetId(id)    save(u)    //println egetMessage()    }       return ugetId()    }       def delete(u) {    try {    def id = ugetId()    def sql = connect()    def result = sqlexecute(DELETE FROM ` + tablename + ` WHERE id= + id);    println delete operation completed!    } catch (Exception e) {    println egetMessage()    }    }       def findBy(classname condition) {    def sql = connect()    objs = []    sqleachRow( select * from + pointToLine(classname) + where + condition) {    obj = ClassforName(classname)newInstance()       def clazz = objgetClass()    def fields = clazzgetDeclaredFields()    def methods = clazzgetDeclaredMethods()    for (f in fields) {    def fstr = ftoString()    if (fstrstartsWith( private )) {    def fieldname = fstrsubstring(fstrlastIndexOf( ) + )    def setmethodname = set + capitalize(fieldname)    def setmethod    for (m in methods) {    def methodname = mtoString()    if (ntains(setmethodname)) {    setmethod = m    }    }    def fieldvalue = itgetProperty(fieldname)    setmethodinvoke(obj fieldvalue)    }    }       objsadd(obj)    }       return objs    }       println Id of the saved object is + save(user)    println Found + findBy( eduecustormUser id = )    userToDelete = new User( Daniel )    delete(userToDelete)   


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

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