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

MyBatis メモ

Posted at

MyBatisの基本構成

・Mapper Interface Javaのインタフェース。SQLと対応
・Mapper XML 実際のSQLを書くファイル
・Entity(Model) データベースのテーブルに対応するJavaクラス
・SqlSession / Spring Boot 実行エンジン(SpringではDIで自動化)

1.Entity クラスの作成(例:User)

public class User {
    private int id;
    private String name;
    private int age;

    // getter/setter
}

2.Mapper インタフェース(UserMapper.java)

public interface UserMapper {
    User findById(int id);
    List<User> findAll();
    void insertUser(User user);
    void updateUser(User user);
    void deleteUser(int id);
}

3.Mapper XML ファイル(UserMapper.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.mapper.UserMapper">

  <select id="findById" resultType="User">
    SELECT * FROM users WHERE id = #{id}
  </select>

  <select id="findAll" resultType="User">
    SELECT * FROM users
  </select>

  <insert id="insertUser">
    INSERT INTO users (name, age) VALUES (#{name}, #{age})
  </insert>

  <update id="updateUser">
    UPDATE users SET name = #{name}, age = #{age} WHERE id = #{id}
  </update>

  <delete id="deleteUser">
    DELETE FROM users WHERE id = #{id}
  </delete>

</mapper>

4.Spring Bootでの使用例(ServiceやControllerで)

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    public void addUser(User user) {
        userMapper.insertUser(user);
    }
}

●よく使うSQLの書き方パターン
1.条件付き検索(<where>/ <if>)

<select id="searchUser" resultType="User">
  SELECT * FROM users
  <where>
    <if test="name != null">
      AND name = #{name}
    </if>
    <if test="age != null">
      AND age = #{age}
    </if>
  </where>
</select>

2.自動採番の主キーを取得(MySQL)

<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
  INSERT INTO users (name, age) VALUES (#{name}, #{age})
</insert>

3.リストのIN句検索(<foreach>)

<select id="findByIds" resultType="User">
  SELECT * FROM users WHERE id IN
  <foreach item="id" collection="idList" open="(" separator="," close=")">
    #{id}
  </foreach>
</select>

●MyBatisでプロシージャを呼び出す基本構成
・Mapper インタフェース 呼び出し定義(メソッド)
・Mapper XML タグで CALL プロシージャ名 を実行
・パラメータクラス(ParameterBean) IN/OUT用のJavaオブジェクト

例)ストアドプロシージャ

-- MySQL / Oracle の例(OUTパラメータ付き)
CREATE PROCEDURE get_user_name (
  IN user_id INT,
  OUT user_name VARCHAR(100)
)
BEGIN
  SELECT name INTO user_name FROM users WHERE id = user_id;
END;

1.パラメータ用Javaクラス(ParameterBean)

public class UserParam {
    private int userId;       // IN
    private String userName;  // OUT

    // Getter / Setter
}

2.Mapperインタフェース

public interface UserMapper {
    void getUserName(UserParam param);
}

3.Mapper XML の定義(UserMapper.xml)

<mapper namespace="com.example.mapper.UserMapper">

  <select id="getUserName" statementType="CALLABLE" parameterType="UserParam">
    { call get_user_name(#{userId, mode=IN, jdbcType=INTEGER},
                         #{userName, mode=OUT, jdbcType=VARCHAR}) }
  </select>

</mapper>

4.呼び出し側(Serviceなど)

UserParam param = new UserParam();
param.setUserId(1);

userMapper.getUserName(param);

System.out.println("ユーザー名: " + param.getUserName());

Mapper XML で NEXTVAL を使う

<insert id="insertUser" parameterType="User">
  INSERT INTO users (id, name, age)
  VALUES (user_seq.NEXTVAL, #{name}, #{age})
</insert>
0
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
0
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?