原创不易,请标明出处: https://blog.csdn.net/rocklee/article/details/124884801
目录- 1、新的counter分析器
- 2、新的MySqlDialect
- 3、在适当的时机注册新的言语处理器
select for update 应该不少人会用到,用于更新前的锁定,按理来讲PageHelper只是查询分页,所以它没考虑到也是可以理解的(版本5.3.0),具体问题:
https://github.com/pagehelper/Mybatis-PageHelper/issues/671
Raw sql: select * from stock_tbl st where commodity_code >='c002' order by commodity_code for update 我期望得到的分布sql: select * from stock_tbl st where commodity_code >='c002' order by commodity_code limit ? offset ? for update 但是pagehelper转换得到的sql: select id, commodity_code, count from stock_tbl order by commodity_code for update LIMIT ? offset ? PageHelper 版本: 5.3.0
就是它的 limit offset放的地方没考虑到for update子句。
但是阿里的seata这个分布式事务锁,若要避免所谓脏读必须要@GlobalLock+select for update ,没办法,只能改PageHelper。
PageHelper套件改起来还是挺好改的,它通过PageAutoDialect.registerDialectAlias来注册各种数据库言语处理器,所以当我觉得它的mysql语法处理不行就用这个方法把mysql方言处理器替换掉即可。
1、新的counter分析器因为我不希望select count的时候带上for update,所以要重写它。
public class CountSqlParserEx extends CountSqlParser {
@Override
public void processPlainSelect(PlainSelect plainSelect) {
if (!orderByHashParameters(plainSelect.getOrderByElements())) {
plainSelect.setOrderByElements(null);
}
if (plainSelect.getFromItem() != null) {
processFromItem(plainSelect.getFromItem());
}
if (plainSelect.isForUpdate()){
plainSelect.setForUpdate(false);
}
if (plainSelect.getJoins() != null && plainSelect.getJoins().size() > 0) {
List joins = plainSelect.getJoins();
for (Join join : joins) {
if (join.getRightItem() != null) {
processFromItem(join.getRightItem());
}
}
}
}
}
2、新的MySqlDialect
重写getPageSql段,将 for updaqte子句移到最后。
public class MySqlDialectEx extends MySqlDialect {
public MySqlDialectEx() {
countSqlParser=new CountSqlParserEx();
}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {
Statement stmt = null;
try {
stmt = CCJSqlParserUtil.parse(sql);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
boolean isSelectUpdate=false;
Select select = (Select) stmt;
SelectBody selectBody = select.getSelectBody();
if (selectBody instanceof PlainSelect){
PlainSelect plainSelect=(PlainSelect) selectBody;
isSelectUpdate=plainSelect.isForUpdate();
if (isSelectUpdate){
plainSelect.setForUpdate(false);
}
}
sql=select.toString();
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
if (page.getStartRow() == 0) {
sqlBuilder.append("n LIMIT ? ");
} else {
sqlBuilder.append("n LIMIT ?, ? ");
}
if (isSelectUpdate){
sqlBuilder.append(" for update");
}
return sqlBuilder.toString();
}
}
3、在适当的时机注册新的言语处理器
写一个配置类,在PageHelperAutoConfiguration装配之前打上这个补丁。
@Configuration
@ConditionalOnClass(PageAutoDialect.class)
@AutoConfigureBefore(value = PageHelperAutoConfiguration.class)
public class PageHelperConfig {
public PageHelperConfig() {
PageAutoDialect.registerDialectAlias("mysql", MySqlDialectEx.class);
}
}
完



