Error Logs๐Ÿพ

JPA casecade ์—๋Ÿฌ

hae02y 2023. 9. 17. 02:37
๋ฐ˜์‘ํ˜•

error log

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.codestates.server.domain.license.licensedate.entity.License.licenseInfo -> com.codestates.server.domain.license.licenseinfo.entity.LicenseInfo; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.codestates.server.domain.license.licensedate.entity.License.licenseInfo -> com.codestates.server.domain.license.licenseinfo.entity.LicenseInfo

JPA ์—ฐ๊ด€๊ด€๊ณ„ ํ…Œ์ŠคํŠธ์ค‘ ๋ฐœ์ƒํ•˜๋Š” ์˜ค๋ฅ˜๋กœ ๋ฐœ์ƒ ์ด์œ ๋Š”
FK๋กœ ์‚ฌ์šฉ๋˜๋Š” ์ปฌ๋Ÿผ๊ฐ’์ด ์—†๋Š” ์ƒํƒœ์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ์œผ๋ ค๋‹ค ๋ฐœ์ƒํ•˜๋Š”์—๋Ÿฌ์ด๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด Person (id, name) ์ด๋ผ๋Š” ํ…Œ์ด๋ธ”๊ณผ Home (id, address, person_id) ๋ผ๋Š” ํ…Œ์ด๋ธ” ๊ด€๊ณ„๊ฐ€ ์žˆ์„ ๋•Œ, Person ๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ์ง€ ์•Š๊ณ  Home ๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ์œผ๋ ค๊ณ  ํ•œ๋‹ค๋ฉด, person_id ๊ฐ’์ด ์—†์–ด์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๊ฒŒ ๋œ๋‹ค.

Person person = new Person("haeyoung");
Home home = new Home("Daejeon", person);

homeRepository.save(home);  //person์— id ๊ฐ’์ด ์•ˆ๋“ค์–ด๊ฐ€์žˆ์–ด์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

JPA์—์„œ ์—ฐ๊ด€ ๊ด€๊ณ„ ๋งคํ•‘์„ ํ• ๋•Œ ์‚ฌ์šฉํ•˜๋Š” @ManyToOne, @OneToOne, @OneToMany ์–ด๋…ธํ…Œ์ด์…˜์— cascade ์˜ต์…˜์„ ์„ค์ •ํ•ด์ฃผ์–ด์•ผํ•œ๋‹ค.

cascade ๋Š” "์˜์†์„ฑ ์ „์ด" ๋ผ๊ณ  ํ•˜๋Š” ๊ฐœ๋…์ธ๋ฐ ํŠน์ • ์—”ํ‹ฐํ‹ฐ๋ฅผ ์˜์†ํ™” ํ•  ๋•Œ ์—ฐ๊ด€๋œ ์—”ํ‹ฐํ‹ฐ๋„ ํ•จ๊ป˜ ์˜์†์‹œํ‚จ๋‹ค.

Casecade ์ข…๋ฅ˜

  • ALL
  • PERSIST
  • REMOVE
  • MERGE
  • REFERESH
  • DETACH

์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” ๊ฒƒ์€ ALL๊ณผ PERSIST์ด๋‹ค. ALL์€ ์œ„์˜ ๋ชจ๋“  ์˜์†์„ฑ์ด ์ „์ด๋˜๋Š” ๊ฒฝ์šฐ์— ์‚ฌ์šฉ๋˜๊ณ , PERSIST๋Š” ์—”ํ‹ฐํ‹ฐ๊ฐ€ ์ €์žฅ๋ ๋•Œ๋งŒ ์—ฐ์‡„์ ์œผ๋กœ ์ €์žฅ๋˜๊ฒŒ ํ•˜๋Š” ์˜ต์…˜์ด๋‹ค.

์–ธ์ œ ์‚ฌ์šฉํ•˜๋ฉด๋˜๋Š”๊ฐ€?

Casecade๋ฅผ ์–ธ์ œ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์„๊นŒ? 1:N ์—ฐ๊ด€๊ด€๊ณ„๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์—ฐ๊ด€๊ด€๊ณ„์˜ ์ฃผ์ธ์€ ํ•ญ์ƒ N์— ์กด์žฌํ•œ๋‹ค. ์ฆ‰ N๊ฐ€ ์•„๋‹Œ 1์— ์‚ฌ์šฉํ•˜๋ฉด ๋˜๋Š”๊ฒƒ์ด๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด


์œ„์˜ ๊ด€๊ณ„์—์„œ Post์™€ Comment๋Š” 1:N ๊ด€๊ณ„์ด๋‹ค. ์ด๊ฒƒ์„ 2๊ฐ€์ง€ ๊ด€์ ์œผ๋กœ ์„ค๊ณ„ํ• ์ˆ˜์žˆ๋‹ค.

  1. Post๊ฐ€ ์‚ฌ๋ผ์ง€๋”๋ผ๋„ Comment๋Š” ์œ ์ง€๋˜๋Š”๊ฒฝ์šฐ
  2. Post๊ฐ€ ์‚ฌ๋ผ์ง€๋ฉด Comment๋„ ์‚ฌ๋ผ์ง€๋Š” ๊ฒฝ์šฐ (Casecade ์ ์šฉ)

1 ์˜ ๊ฒฝ์šฐ์—๋Š” Post์ž‘์„ฑ์ž๊ฐ€ Post๋ฅผ ์‚ญ์ œํ•ด๋„ Comment ์ž‘์„ฑ์ž๋Š” ์ž์‹ ์ด ์ผ๋˜ ๋Œ“๊ธ€์„ ํ™•์ธํ• ์ˆ˜์žˆ๋‹ค.

2 ์˜ ๊ฒฝ์šฐ์—๋Š” Post์ž‘์„ฑ์ž๊ฐ€ Post๋ฅผ ์‚ญ์ œํ•˜๊ฒŒ๋œ๋‹ค๋ฉด Comment ์ž‘์„ฑ์ž๋Š” ์ž์‹ ์ด ์ผ๋˜ Comment๋ฅผ ํ™•์ธํ• ์ˆ˜์—†๋‹ค. ์ด๋ ‡๊ฒŒ ์„ค๊ณ„๋˜๋Š”๊ฒฝ์šฐ @OneToMany List<Comment> ์— Casecade
๋ฅผ ๊ฑธ๋ฉด ๋˜๋Š”๊ฒƒ์ด๋‹ค.

๋ฐ˜์‘ํ˜•