Skip to content

Instantly share code, notes, and snippets.

@wendal
Created September 10, 2015 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wendal/54718283670e4f5fd411 to your computer and use it in GitHub Desktop.
Save wendal/54718283670e4f5fd411 to your computer and use it in GitHub Desktop.
演示如何得到NutDao生成的Sql语句
@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);
}
}
@wendal
Copy link
Author

wendal commented Dec 4, 2016

1.r.58已经不需要这种方式,通过dao拦截器可以轻松实现

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment