LoginSignup
1
1

More than 3 years have passed since last update.

MyBatis で 自動採番されたキーを取得する際にハマった話

Last updated at Posted at 2020-11-01

MySQLのAUTO_INCREMENTで自動裁判されたID(主キー)をオブジェクトにセットしようとしたら、1がセットされてしまった。

ドメインクラス

Hoge.java

@Data 
@NoArgsConstructor
public class Hoge{
    private Integer id;
    private String message;
}

サービスクラス

HogeService.java
public class HogeService{

    @Autowired
    private HogeMapper hogeMapper;    

    public addHoge(){

        Hoge hoge = new Hoge();
        hoge.setMessage("Hello");

        hoge.setId(hogeMapper.insert());

        System.out.println(hoge.getId());//1
        //IDが1になってしまう。
    }
} 

マッパー

HogeMapper.java

@Mapper
public interface HogeMapper{
    Integer insert(Hoge hoge);
}
HogeMapper.xml
    <insert id="insert">
        INSERT INTO hoge(id, message)
        VALUES (#{id}, #{message})
        <selectKey resultType="Integer" keyProperty="id" order="AFTER">
            select @@IDENTITY
        </selectKey>
    </insert>

上記の方法だと、hogeに1のみセットされてしまう。

MyBatisの selectKey はオブジェクトに直接代入されるため、下記コードにすればIDが取得できる。

HogeService.java
public class HogeService{

    @Autowired
    private HogeMapper hogeMapper;    

    public addHoge(){

        Hoge hoge = new Hoge();
        hoge.setMessage("Hello");

        hogeMapper.insert();

        System.out.println(hoge.getId());
        //自動採番されたIDが出力される!!
    }
} 

まとめ

MybatisのSELECT KEYはオブジェクトに直接代入される。

1
1
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
1
1