Created
September 10, 2015 03:00
-
-
Save wendal/54718283670e4f5fd411 to your computer and use it in GitHub Desktop.
演示如何得到NutDao生成的Sql语句
This file contains 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
@Test | |
public void test_get_sql() throws Throwable { | |
NutDao dao = new NutDao(ioc.get(javax.sql.DataSource.class)); | |
final List<String> sqls = new ArrayList<String>(); | |
final Method m = NutStatement.class.getDeclaredMethod("toStatement", Object[][].class, String.class); | |
m.setAccessible(true); | |
dao.setExecutor(new DaoExecutor() { | |
public void exec(Connection conn, DaoStatement st) { | |
String psql = st.toPreparedStatement(); | |
sqls.add(psql); | |
// 如果需要带数据的, 因为nutz并不生成和执行带数据的sql,所以需要通过 | |
// st.toPreparedStatement() 与 参数矩阵 st.getParamMatrix() 综合生成 | |
// 这里调用非公开api中的toStatement | |
// 事实上根据参数矩阵(getParamMatrix)和Sql语句(toPreparedStatement)就能逐一替换生成 | |
try { | |
String ssql = (String) m.invoke(st, st.getParamMatrix(), psql); | |
sqls.add(ssql); | |
} | |
catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
}); | |
dao.insert(Pet.create("hi")); // 对于那些需要返回基本数据类型的方法来说,这里肯定抛异常,但不影响获取sql | |
for (String sql : sqls) { | |
System.out.println(sql); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
1.r.58已经不需要这种方式,通过dao拦截器可以轻松实现