LoginSignup
8
10

More than 5 years have passed since last update.

MyBatis 3.4.2からMapperインタフェースでdefaultメソッドが使えるようになるよ!

Last updated at Posted at 2016-09-19

(まだリリースされてませんが)MyBatis 3.4.2からJava SE 8からサポートされたdefaultメソッドが利用できるようになります。いろいろな使い方があると思いますが、ここでは、Spring DataのAPIを利用したページ検索メソッドの実装例を紹介します。自分はMapperインタフェースをRepositoryインタフェースとして代用することがあるので、この仕組みはちょっと嬉しいです。

import com.example.domain.Todo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.session.RowBounds;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import java.util.Collections;
import java.util.List;

@Mapper
public interface TodoRepository {

    @Select("SELECT COUNT(id) FROM todo")
    long count();

    @Select("SELECT id, title, details, finished FROM todo ORDER BY id")
    List<Todo> findRangeList(RowBounds rowBounds);

    // ↓ defaultメソッドを使ってSpring DataのAPIを利用したページ検索メソッドを実装してみると・・・
    default Page<Todo> findPage(Pageable pageable){
        long total = count();
        List<Todo> list = Collections.emptyList();
        if (total > 0) {
            list = findRangeList(new RowBounds(pageable.getOffset(), pageable.getPageSize()));
        }
        return new PageImpl<>(list, pageable, total);
    }

}
SNAPSHOTバージョンを使うためのpom.xmlの定義例
<dependencies>
    <!-- ... -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.2-SNAPSHOT</version>
    </dependency>
    <!-- ... -->
</dependencies>
<repositories>
    <repository>
        <id>sonatype-oss-snapshots</id>
        <name>Sonatype OSS Snapshots Repository</name>
        <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </repository>
</repositories>

今回は簡単な紹介でしたが、MyBatis 3.4.2が正式にリリースされたら、ちゃんとまとめたいと思います。

8
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
10