[SA — 101] การเชื่องโยงความสัมพันธ์ระหว่าง Entity

Phumai Chanphunga
Sep 6, 2018 · 2 min read

การเชื่องโยงความสัมพันธ์ระหว่าง Entity

class diagram ระดับ analysis

จากตอนที่เเล้ว เราได้เริ่มสร้าง entity ใน spring boot เเล้วใช้ H2 ในการดูว่า class entity เราถูกสร้างเป็น table ถูกไหม (เเต่จริงๆถ้า build ผ่านมันก็สร้างให้เเหละ )

ในส่วนนี้จะเป็นการเเนะนำวิธีทำการเชื่อมความสัมพันธ์ระหว่าง entity เราจะยกตัวอย่างจาก

ขั้นตอนการทำ

  1. สร้าง entity ที่มีเเต่ละตัว
  2. โยงความสัมพันธ์

1. สร้าง entity ที่มีเเต่ละตัว

สร้าง entity class User , Comment , Video

User.java

Comment.java

Video.java

พอ run ทดสอบก็จะขึ้น table ให H2

2. โยงความสัมพันธ์

class diagram ระดับ analysis

Comment มีความสัมพันเเบบ ManyToOne กับ Video
Comment มีความสัมพันเเบบ ManyToOne กับ User
Video มีความสัมพันเเบบ ManyToOne กับ User

Commem.java update

Video.java update

  • one to many with comment
  • many to one with user

User.java update

  • one to many with comment
  • one to many with video

การเขียนความสัมพันธ์จะทำการ mappedBy คือการ bind ทั้งสองฝังทำให้ค่ามีความสัมพันธ์กัน

orphanRemoval คือเมื่อตารางหลังหาย ตารางองค์ประกอบก็หายด้วย

ref : อ่านเพิ่มเติม เเบบ one to one

つづく

Phumai Chanphunga

Written by

Full Stack sleepper Computer En

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade