Search

useGeneratedKeys

useGeneratedKeys

MyBatis์˜ ๋งคํผ XML์—์„œย useGeneratedKeys์™€ย keyPropertyย ์†์„ฑ์„ ์„ค์ •ํ•˜์—ฌ,ย INSERTย ์‹คํ–‰ ํ›„์— ์ž๋™์œผ๋กœ ์ฆ๊ฐ€๋œ ํ‚ค ๊ฐ’์„ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
<!-- UserMapper.xml --> <insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> INSERT INTO User (name, email) VALUES (#{name}, #{email}) </insert>
Java
๋ณต์‚ฌ

1. ํ…Œ์ด๋ธ” ์„ค์ •

MySQL์—์„œย AUTO_INCREMENT๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ํ…Œ์ด๋ธ”์ด ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ดย idย ์ปฌ๋Ÿผ์ด ๊ธฐ๋ณธ ํ‚ค์ด๋ฉฐ ์ž๋™ ์ฆ๊ฐ€๋˜๋Š”ย Userย ํ…Œ์ด๋ธ”์„ ๊ฐ€์ •ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
sql ์ฝ”๋“œ ๋ณต์‚ฌ CREATE TABLE User ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), email VARCHAR(50) );
SQL
๋ณต์‚ฌ

2. Mapper XML ์„ค์ •

MyBatis์˜ ๋งคํผ XML์—์„œย useGeneratedKeys์™€ย keyPropertyย ์†์„ฑ์„ ์„ค์ •ํ•˜์—ฌ,ย INSERTย ์‹คํ–‰ ํ›„์— ์ž๋™์œผ๋กœ ์ฆ๊ฐ€๋œ ํ‚ค ๊ฐ’์„ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
xml ์ฝ”๋“œ ๋ณต์‚ฌ <!-- UserMapper.xml --><insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> INSERT INTO User (name, email) VALUES (#{name}, #{email}) </insert>
XML
๋ณต์‚ฌ
โ€ข
useGeneratedKeys: MyBatis์—๊ฒŒ ์ƒ์„ฑ๋œ ํ‚ค๋ฅผ ๊ฐ€์ ธ์˜ค๋„๋ก ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.
โ€ข
keyProperty: ๋ฐ˜ํ™˜๋œ ์ž๋™ ์ฆ๊ฐ€ ํ‚ค๋ฅผ ๋งคํ•‘ํ•  ๊ฐ์ฒด์˜ ์†์„ฑ ์ด๋ฆ„์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์„œ๋Š”ย Userย ๊ฐ์ฒด์˜ย idย ํ•„๋“œ๊ฐ€ ์ž๋™ ์ฆ๊ฐ€๋œ ๊ฐ’์„ ๋ฐ›๋„๋ก ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

3. User ํด๋ž˜์Šค ์ž‘์„ฑ

Userย ํด๋ž˜์Šค์—ย id,ย name,ย emailย ์†์„ฑ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.
java ์ฝ”๋“œ ๋ณต์‚ฌ public class User { private Integer id;// PK ํ•„๋“œprivate String name; private String email; // Getter, Setter ์ƒ๋žต }
Java
๋ณต์‚ฌ

4. Mapper ์ธํ„ฐํŽ˜์ด์Šค ์ž‘์„ฑ

MyBatis ๋งคํผ ์ธํ„ฐํŽ˜์ด์Šค์—ย insertUserย ๋ฉ”์„œ๋“œ๋ฅผ ์„ ์–ธํ•ฉ๋‹ˆ๋‹ค.
java ์ฝ”๋“œ ๋ณต์‚ฌ @Mapper public interface UserMapper { void insertUser(User user); }
Java
๋ณต์‚ฌ

5. ์„œ๋น„์Šค์—์„œ ํ˜ธ์ถœํ•˜๊ธฐ

์„œ๋น„์Šค ๊ณ„์ธต์—์„œย insertUserย ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•œ ํ›„ย user.getId()๋ฅผ ํ†ตํ•ดย AUTO_INCREMENT๋œ ํ‚ค ๊ฐ’์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
java ์ฝ”๋“œ ๋ณต์‚ฌ @Service public class UserService { @Autowired private UserMapper userMapper; public Integer createUser(String name, String email) { User user = new User(); user.setName(name); user.setEmail(email); userMapper.insertUser(user); // INSERT ํ›„ ์ž๋™ ์ฆ๊ฐ€๋œ PK ๊ฐ’return user.getId(); } }
Java
๋ณต์‚ฌ

์ฃผ์˜ ์‚ฌํ•ญ

โ€ข
MyBatis ๋ฒ„์ „์— ๋”ฐ๋ผย useGeneratedKeysย ์˜ต์…˜์„ ์ง€์›ํ•˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, ์ตœ์‹  ๋ฒ„์ „์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค.
โ€ข
MySQL ์ด์™ธ์˜ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ๋„ ์œ ์‚ฌํ•œ ์„ค์ •์œผ๋กœ ์ ์šฉํ•  ์ˆ˜ ์žˆ์ง€๋งŒ, ๊ฐ DBMS์˜ ํ‚ค ์ƒ์„ฑ ๋ฐฉ์‹์— ๋”ฐ๋ผ ์ถ”๊ฐ€ ์„ค์ •์ด ํ•„์š”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
์ด๋ ‡๊ฒŒ ์„ค์ •ํ•˜๋ฉด MyBatis๊ฐ€ย INSERTย ํ›„์— ์ž๋™์œผ๋กœ ์ฆ๊ฐ€๋œ ๊ธฐ๋ณธ ํ‚ค ๊ฐ’์„ย Userย ๊ฐ์ฒด์˜ย idย ํ•„๋“œ์— ์ฑ„์›Œ์ฃผ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.