Mybatis Interceptor 자동 Paging처리 만들기(1) 바로가기
Mybatis Interceptor 자동 Paging처리 사용방법
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
MetaObject metaStatementHandler = MetaObject.forObject(statementHandler,
DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
PageInfo pageInfo = (PageInfo) metaStatementHandler.getValue("delegate.rowBounds");
String originalSql = (String) metaStatementHandler.getValue("delegate.boundSql.sql");
// limit 추가된 query
metaStatementHandler.setValue("delegate.boundSql.sql", attachQuery(originalSql, pageInfo));
} catch (ClassCastException e) {}
return invocation.proceed();
}
PrepareInterceptor가 하는일은 추가적으로 Custom하게 Query를 붙이는 것이다.
private String attachQuery(String originalSql, PageInfo pageInfo) {
if (pageInfo.getTotalCount() == -1)
return attachCountQuery(originalSql, pageInfo);
if (!isNullPageInfo(pageInfo))
return attachLimitQuery(originalSql, pageInfo);
return originalSql;
}
private String attachCountQuery(String originalSql, PageInfo pageInfo) {
StringBuilder sb = new StringBuilder("SELECT COUNT(*) FROM ( ");
sb.append(originalSql);
sb.append(" ) COUNT_TABLE ");
String attachedCountQuery = sb.toString();
return attachedCountQuery;
}
Wrapper 형식으로 감싸서 Count Query 생성
private String attachLimitQuery(String originalSql, PageInfo pageInfo) {
StringBuilder sb = new StringBuilder(originalSql);
sb.append(" LIMIT ");
sb.append((pageInfo.getPage() - 1) * pageInfo.getSize());
sb.append(", ");
sb.append(pageInfo.getSize());
String attachLimitQuery = sb.toString();
return attachLimitQuery;
}