When I tried to set the ID (primary key) that was automatically tried by MySQL AUTO_INCREMENT to the object, 1 was set.
Domain class
Hoge.java
@Data
@NoArgsConstructor
public class Hoge{
private Integer id;
private String message;
}
Service class
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
//The ID will be 1.
}
}
Mapper
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>
With the above method, only 1 is set in hoge.
Since the selectKey of MyBatis is directly assigned to the object, you can get the ID by using the code below.
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());
//The automatically numbered ID is output! !!
}
}
Mybatis SELECT KEY is assigned directly to the object.
Recommended Posts