Created
June 22, 2012 05:13
-
-
Save wendal/2970374 to your computer and use it in GitHub Desktop.
Nutz VoSqlCallback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.nutz.dao; | |
import java.lang.reflect.Field; | |
import java.sql.Connection; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.util.ArrayList; | |
import java.util.List; | |
import org.nutz.castor.Castors; | |
import org.nutz.dao.sql.Sql; | |
import org.nutz.dao.sql.SqlCallback; | |
import org.nutz.lang.Lang; | |
public class PojoTest { | |
public void test() { | |
Dao dao = null; | |
Sql sql = Sqls.create("XXXX"); | |
sql.setCallback(new VoCallback(UserVo.class)); | |
dao.exec(sql); | |
List<UserVo> = sql.getList(UserVo.class); | |
} | |
} | |
class VoCallback implements SqlCallback { | |
private Class<?> klass; | |
public VoCallback(Class<?> klass) { | |
this.klass = klass; | |
} | |
public Object invoke(Connection conn, ResultSet rs, Sql sql) | |
throws SQLException { | |
List list = new ArrayList(); | |
while(rs.next()) { | |
try { | |
Object obj = klass.newInstance(); | |
Field[] fields = klass.getDeclaredFields(); | |
for (Field field : fields) { | |
Object f = rs.getObject(field.getName()); | |
if (f != null) | |
field.set(obj, Castors.me().castTo(f, field.getType())); | |
} | |
list.add(obj); | |
} catch (Throwable e) { | |
throw Lang.wrapThrow(e); | |
} | |
} | |
return list; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment