my batis - plus 고급 기능 사용자 정의 통용 방법 상세 설명
32321 단어 자바 개인 노트자바mybatismybatis-plus
MP 는 처음부터 많은 일반적인 방법 을 제공 해 왔 습 니 다. DefaultSqlInjector 라 는 클래스 에 MethodList 라 는 집합 에 포 함 된 것 은 모두 일반적인 방법 클래스 입 니 다. 사용자 정의 통용 방법 을 사용 하려 면 이 집합 에 추가 해 야 합 니 다.
/**
* SQL
*
* @author hubin
* @since 2018-04-10
*/
public class DefaultSqlInjector extends AbstractSqlInjector {
@Override
public List<AbstractMethod> getMethodList() {
return Stream.of(
new Insert(),
new Delete(),
new DeleteByMap(),
new DeleteById(),
new DeleteBatchByIds(),
new Update(),
new UpdateById(),
new SelectById(),
new SelectBatchByIds(),
new SelectByMap(),
new SelectOne(),
new SelectCount(),
new SelectMaps(),
new SelectMapsPage(),
new SelectObjs(),
new SelectList(),
new SelectPage()
).collect(toList());
}
}
사용자 정의 방법 구현 - 삭제 시 채 우기 예:
/**
* @auther: zpq
* @date: 2020/11/9 19:55
* @description:
*/
public class DelFillUserMethod extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(
Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
//
String userId = UserContext.getCurrent() == null ? null : UserContext.getCurrent().getId2();
String userName = UserContext.getCurrent() == null ? null : UserContext.getCurrent().getName();
// set
String set = "set useflag = 0,deletetime = now(),operatetime = now()";
if (StringUtils.isNotBlank(userId)) set += ",set deleterid = " + userId;
if (StringUtils.isNotBlank(userName)) set += ",set deleter = " + userName;
//
CustomSqlMethod sqlMethod = CustomSqlMethod.DEL_FILL_USER;
/** * sql */
String sql =
String.format(
// sql
sqlMethod.getSql(),
//
tableInfo.getTableName(),
// set
set,
// ( )
tableInfo.getKeyColumn(),
//
tableInfo.getKeyProperty(),
// and = yes | false and = no
tableInfo.getLogicDeleteSql(true, true));
// SQL
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
// mp
return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
}
}
/**
* @auther: zpq
* @date: 2020/11/10 14:29
* @description: sql
*/
public enum CustomSqlMethod {
/**
*
*/
INSERT_ONE("insert", " ( )", "
INSERT INTO %s %s VALUES %s
"),
/**
*
*/
DELETE_BY_ID("deleteById", " ID ", "
DELETE FROM %s WHERE %s=#{%s}
"),
/**
*
*/
LOGIC_DELETE_BY_ID("deleteById", " ID ", "
UPDATE %s %s WHERE %s=#{%s} %s
"),
/**
* ->
*/
DEL_FILL_USER("delFillUser", " ", "
UPDATE %s %s WHERE %s=#{%s} %s
"),
BATCH_DEL_FILL_USER("batchDelFillUser", " ", "
UPDATE %s %s WHERE %s IN (%s) %s
"),
/**
*
*/
SELECT_OBJS("selectObjs", " ", "%s SELECT %s FROM %s %s %s
");
private final String method;
private final String desc;
private final String sql;
CustomSqlMethod(String method, String desc, String sql) {
this.method = method;
this.desc = desc;
this.sql = sql;
}
public String getMethod() {
return method;
}
public String getDesc() {
return desc;
}
public String getSql() {
return sql;
}
}
methodList
에 사용자 정의 방법 을 추가 해 야 합 니 다 /**
* @auther: zpq
* @date: 2020/11/9 20:00
* @description: sql
* mp
*/
@Component
public class CustomSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
// , , ,
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
/***
*
*/
methodList.add(new DelFillUserMethod());
methodList.add(new BatchDelFillUserMethod());
return methodList;
}
}
/**
* @Description:
*
* @param: id id
* @auther: zpq
* @date: 2020/11/10 11:47
*/
int delFillUser(Serializable id);
SuperMapper
을 만 들 고 BaseMapper 를 계승 합 니 다. 그러면 이 방법 을 사용 한 mapper 는 SuperMapper 만 계승 하면 됩 니 다. 다음 과 같 습 니 다. /**
* @auther: zpq
* @date: 2020/11/9 20:10
* @description: mapper
*/
public interface SuperMapper<T> extends BaseMapper<T> {
/**
* @Description:
*
* @param: id id
* @auther: zpq
* @date: 2020/11/10 11:47
*/
int delFillUser(Serializable id);
/**
* @Description:
*
* @param: idList ID ( null empty)
* @auther: zpq
* @date: 2020/11/10 3:12
*/
int batchDelFillUser(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
}
/**
* @auther: zpq
* @date: 2020/11/10 14:59
* @description:
*/
public class BatchDelFillUserMethod extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(
Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
//
String userId = UserContext.getCurrent() == null ? null : UserContext.getCurrent().getId2();
String userName = UserContext.getCurrent() == null ? null : UserContext.getCurrent().getName();
// sql
String set = "set useflag = 0,deletetime = now(),operatetime = now()";
if (StringUtils.isNotBlank(userId)) set += ",set deleterid = " + userId;
if (StringUtils.isNotBlank(userName)) set += ",set deleter = " + userName;
// sql
CustomSqlMethod sqlMethod = CustomSqlMethod.BATCH_DEL_FILL_USER;
// sql
String sql =
String.format(
sqlMethod.getSql(),
tableInfo.getTableName(),
set,
tableInfo.getKeyColumn(),
// foreach in(ids)
SqlScriptUtils.convertForeach("#{item}", COLLECTION, null, "item", COMMA),
tableInfo.getLogicDeleteSql(true, true));
// SQL
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
}
}
끝 말:
여기까지
mybatis-plus
끝 났 습 니 다. 사실은 간단 합 니 다. 다른 방법 을 쓰 는 것 도 마찬가지 입 니 다. my batis - plus 소스 코드 를 대조 해서 베 끼 면 됩 니 다. 하하 하...
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
【eclipse】같은 파일을 2개 열고 싶다【에디터의 분할】「이런 것은 다른 클래스로 나누어야 한다!」라든지 있다고는 생각합니다만. 실제로 실무 속에서 프로그램을 쓰고 있으면, 이런 소스에 눈에 걸리는 일도 적지 않을까···. 그건 그렇고, 내 노트북에서 이렇게 보입니다 네...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.