springboot が mybatis ページング インターセプターを統合する方法

WBOY
リリース: 2023-05-13 16:31:13
転載
1657 人が閲覧しました

はじめに

今日開発をしていたとき、自分が書いたコードを最適化したいと思いました。開発サーバー上でそれを行いたくなかったので、それによって多くの問題が発生するのではないかと心配していました。実稼働サーバーに関しては、GIT の問題を解決して分離しました。ホイール (ツール) プロジェクトに目を向けると、最後の実行後、リストを取得するときに少なくとも 10 秒間スタックしていることがわかり、ショックを受けました。私の通常バージョンは通常約 800 ミリ秒かかります (データ量が膨大なので、長時間見ないでください。これは正常です)。前提として、それが非常に遅いことはわかっています。最適化を完了したら、最適化されたプラス バージョンをリリースして 10 秒に戻ります。最初にこのアプリ プロジェクトを受け取ったとき、PageHelper .startPage(page, num); (ページング) を使用したとき、データのカプセル化の前にページが分割されました ( PageInfo) が見つかりました。ホイールに切り替えたときにこの問題が見つかりました。制限を SQL に結合するのに役立ちません。後で、すべてを取得してから、PageInfo ページングを実行しました。大量のデータにより、非常に困難になりました。最後に...

10 秒:

springboot が mybatis ページング インターセプターを統合する方法

通常:

springboot が mybatis ページング インターセプターを統合する方法

springboot は mybatis を統合しますページング インターセプター

ページング インターセプトは、実際には SQL を取得し、その SQL を制限に結合することです

pom.xml

   <!-- 引入分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
         <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
ログイン後にコピー

yml

spring:
  application:
    name: spring-cloud-dynamic
  datasource:
    #类型
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/f2f?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: root
    password: 

    initial-size: 2
    max-idle: 10
    min-idle: 1
    max-wait: 60000
    max-active: 20 #最大空闲连接数
    #多久进行一次检测,检测需要关闭的空闲连接
    time-between-eviction-tuns-millis: 60000
ログイン後にコピー

MybatisConfig

/**
 * @author lanys
 * @Description:
 * @date 23/7/2021 下午8:38
 */

@Configuration
@EnableTransactionManagement
@PropertySource(value = "classpath:application.yml", ignoreResourceNotFound = true)
public class MybatisConfig implements TransactionManagementConfigurer {

    @Value("${mybatis.mapper-locations}")
    private String mapper;

    @Value("${mybatis.type-aliases-package}")
    private String aliases;

    @Autowired
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        // 设置数据源
        bean.setDataSource(dataSource);
        // 设置xml
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper));
        // 设置别名
        bean.setTypeAliasesPackage(aliases);
        // 添加分页插件
        bean.setPlugins(new Interceptor[]{pageInterceptor()});
        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return bean.getObject();
    }

    /**
     * 分页拦截器
     * @return
     */
    private PageInterceptor pageInterceptor() {
        PageInterceptor pageInterceptor = new PageInterceptor();
        // 详见 com.github.pagehelper.page.PageParams
        Properties p = new Properties();
        // RowBounds是否进行count查询 - 默认不查询
        p.setProperty("rowBoundsWithCount", "true");
        // 当设置为true的时候,如果page size设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果
        p.setProperty("pageSizeZero", "true");
        // 分页合理化
        p.setProperty("reasonable", "false");
        // 是否支持接口参数来传递分页参数,默认false
        p.setProperty("supportMethodsArguments", "true");
        // 设置数据库方言 , 也可以不设置,会动态获取
        p.setProperty("helperDialect", "mysql");
        pageInterceptor.setProperties(p);
        return pageInterceptor;
    }

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
ログイン後にコピー

Test

私自身のコード

/**
     * 关注列表
     * @param userId
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<DynamicInfo> focusList(Long userId, Integer page, Integer size) {
        PageHelper.startPage(page, size);

        List<DynamicInfo> listByUserId = new ArrayList<>();
        try {
            //获取自己关注列表
            listByUserId = this.dynamicReleaseMapper.getListFocusId(userId);
            if (listByUserId == null || listByUserId.size() == 0){
                return listByUserId;
            }
            //List<DynamicInfo> listByUserId = this.dynamicReleaseMapper.getListFocusId(userId).stream().filter(x->(x.getIsPicture()!=2 && x.getIsVideo() !=2)||(x.getIsPicture()==2 && x.getIsVideo() !=2)||(x.getIsPicture()!=2 && x.getIsVideo() ==2)).collect(Collectors.toList());
            publicGetDynamicInfo(userId,listByUserId);
            //}
            log.info("-------获取关注列表-------");
            return listByUserId;
        } catch (Exception e) {
            log.error("获取关注列表异常",e);
        }
        return listByUserId;
    }
ログイン後にコピー

ページ分割したい場合は、PageHelper.startPage(page, size); を追加します。それ以外の場合、デフォルトではページ分割は行われません。自分で制限を追加することもできます。

結果 (SQL ステートメントの一部が非常に長い):

GROUP BY id ORDER BY create_time desc LIMIT ?
ログイン後にコピー

以上がspringboot が mybatis ページング インターセプターを統合する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:yisu.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!