电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

用Groovy实现最简单的ORM


发布日期:2021/4/20
 
我参加的学校创新试验项目就用它来实现最简易的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)

上一篇:构建器的调用顺序

下一篇:详解JVM内存结构组成