How to use @Update annotation in Spring + MyBatis
assumption
The records in the Employee table should be as follows
ID | NAME | AGE |
---|---|---|
1 | takahashi | 20 |
The dependencies to be selected for the Spring starter project should be as follows
The @Update annotation is added to the method of the interface to which the @Mapper annotation is added.
The @Update annotation describes a SQL statement.
This is a POJO that represents an employee.
package jp.co.confrage.entity; import lombok.Getter; import lombok.Setter; @Setter @Getter public class Employee { private Long id; private String name; private Integer age; }
Mapper interface to manipulate employee tables.
package jp.co.confrage.repository; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Update; @Mapper public interface EmployeeMapper { @Update("update employee set name = #{name}") int update(@Param("name") String name); }
DI is enabled by granting @Mapper annotation.
REST Controller.
package jp.co.confrage.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import jp.co.confrage.repository.EmployeeMapper; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor @RestController public class DemoController { private final EmployeeMapper employeeMapper; @GetMapping("/sample") public String sample() { final var count = employeeMapper.update("yamada"); System.out.println(count); // update件数 return "sample"; } }
Start the Spring Boot application and run the curl command.
curl -X GET http://localhost:8080/sample
The following is standard output
1
コメント