9
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Mapperとは

Posted at

Mapperとは

Javaオブジェクトとデータベースとの間の変換(マッピング)を行うクラス、またはインターフェースを指します。
特にMyBatisを使っている場合、「Mapper」は非常に重要な役割を担います。

MyBatisとは、データベースにアクセスできるフレームワークのことです。

MyBatisにおける「Mapper」の意味

MyBatis では、SQL を XML やアノテーションで定義し、Java インターフェースに「マッピング(対応づけ)」します。
そうすることでデータベース操作を簡単に行えるようにします。
このインターフェースが Mapper です。

例:ユーザー情報を扱う UserMapper

@Mapper
public interface UserMapper{
    @Select("SELECT * FROM users WHERE id = #{id}")
    User findByld(int id);

    @Insert("INSERT INTO users(name, address) VALUES(#{name}, #{address})")
    void insert(User user);
}

例:対応するEntity

public class User{
    private int id;
    private String name;
    private String address;
    // getter/setter
}

よく使われるアノテーション(MyBatis)

アノテーション 説明
@Mapper Mapperインターフェースであることを示す
@Select SELECT文を定義
@Insert INSERT文を定義
@Update UPDATE文を定義
@Delete DELETE文を定義

まとめ

  • SQL と Java の橋渡し
    SQL文とJavaオブジェクト(DTO/Entity)をつなぐ

  • DB操作の抽象化
    select, insert, update, delete などのDB操作を定義

参考

著者: Y.T (株式会社ウィズツーワン)

9
0
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
9
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?