我參加的學校
創新試驗項目
中
就用它來實現最簡易的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