mybatis 中@SelectProvider注解的使用
我看了下与@Select有啥区别,这个@SelectProvider是能够加多条件判断的,看下面的代码示例:
@SelectProvider:用于构建动态查询SQL。
@InsertProvider:用于构建动态新增SQL。
@UpdateProvider:用于构建动态更新SQL。
@DeleteProvider:用于构建动态删除SQL。
type为method对应的方法,其中参数与查询中的参数是一样的本例中都为QueryParam,method为type中对应的返回sql的方法
@SelectProvider(type = SqlProvider.class, method = "count")
int count(@Param("param") QueryParam param);
class SqlProvider {
public String list(QueryParam param) {
return buildQueryParam(param, false);
}
public String count(QueryParam param) {
return buildQueryParam(param, true);
}
private String toDate(Long timestamp) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String startTime = format.format(new Date(timestamp));
return startTime;
}
private String buildQueryParam(QueryParam param, boolean queryCount) {
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append(" select ");
sqlBuilder.append(queryCount ? " count(*) " : " " + FIELD + " ");
sqlBuilder.append(" from " + TABLE + " where 1=1 ");
if (StringUtils.isNotBlank(param.getId())) {
sqlBuilder.append(" and transactionNum='" + param.getId() + "' ");
}
if (StringUtils.isNotBlank(param.getCustomerId())) {
sqlBuilder.append(" and customerId='" + param.getCustomerId() + "' ");
}
if (param.getAssets() != null && param.getAssets().size() > 0) {
String assets = String.join("','", param.getAssets());
sqlBuilder.append(" and coinCode in ('" + assets + "') ");
}
if (null != param.getStartTime() && param.getStartTime() > 0) {
sqlBuilder.append(" and created >= '" + toDate(param.getStartTime()) + "' ");
}
if (null != param.getEndTime() && param.getEndTime() > 0) {
sqlBuilder.append(" and created <= '" + toDate(param.getEndTime()) + "' ");
}
if (null != param.getType()) {
sqlBuilder.append(" and transactionType=" + param.getType().getType());
}
if (null != param.getStatuses() && param.getStatuses().size() > 0) {
if (param.getStatuses().size() == 1) {
sqlBuilder.append(" and status=" + param.getStatuses().get(0).getStatus());
} else {
sqlBuilder.append(" and status in (");
List<String> statusList = param.getStatuses().stream().map(s -> String.valueOf(s.getStatus())).collect(Collectors.toList());
String.join(",", statusList);
sqlBuilder.append(")");
}
}
if (!queryCount) {
sqlBuilder.append(" ORDER BY transactionNum DESC ");
if (null != param.getOffset() && null != param.getLimit()) {
sqlBuilder.append(" limit " + param.getOffset() + "," + param.getLimit());
}
}
return sqlBuilder.toString();
}
}