🗄️ ORM

🗄️ ORM

Object-Relational Mapping · สะพานเชื่อมระหว่าง Code กับ Database


📖 Definition

English — Martin Fowler (Patterns of Enterprise Application Architecture)

“Object-Relational Mapping is a technique for converting data between incompatible type systems using object-oriented programming languages. This creates, in effect, a ‘virtual object database’ that can be used from within the programming language.”

English — Prisma Docs

“An ORM is a library that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique.”

🇹🇭 Thai — สรุปในสไตล์ของตัวเอง

ORM คือ “นักแปลภาษา” ระหว่าง Code ที่เราเขียน กับ Database — แทนที่จะต้องเขียน SQL ตรงๆ เราสามารถดึงข้อมูลผ่าน Object ในภาษาโปรแกรมได้เลย ทำให้โค้ดอ่านง่ายขึ้นและลดโอกาสผิดพลาด 🌸


🔍 Explanation

✍️ เปรียบเทียบ SQL กับ ORM

แบบ SQL ปกติ:

SELECT * FROM users WHERE id = 1;

แบบใช้ ORM (Prisma):

const user = await prisma.user.findUnique({ where: { id: 1 } });

ได้ผลลัพธ์เหมือนกัน แต่อ่านง่ายกว่ามาก

🛠️ ORM ยอดนิยม

ชื่อ ภาษา Database
Prisma JavaScript / TypeScript PostgreSQL, MySQL, SQLite
SQLAlchemy Python หลายประเภท
Hibernate Java หลายประเภท
Sequelize JavaScript MySQL, PostgreSQL

✅ ข้อดี / ⚠️ ข้อควรระวัง

✅ ข้อดี ⚠️ ข้อควรระวัง
เขียนโค้ดเร็วขึ้น Query ซับซ้อนอาจช้ากว่า SQL ตรง
ป้องกัน SQL Injection ต้องเรียนรู้ syntax ของ ORM นั้นๆ
รองรับหลาย Database อาจ hide logic ที่ควรรู้

🤖 GenAI Explanation

“ORM ทำให้ developer ไม่ต้องสลับ mindset ระหว่างโลก OOP กับโลก relational database — เขียนโค้ดเป็น object ตลอด ทำให้ทำงานได้เร็วขึ้นและ bug น้อยลง แต่สำหรับ query ที่ซับซ้อนมาก บางทีกลับไปเขียน SQL ตรงๆ ยังดีกว่า”

ChatGPT (OpenAI)

“ORM เป็นเครื่องมือที่ทรงพลังสำหรับการพัฒนา back-end แต่ควรเข้าใจ SQL พื้นฐานด้วย เพราะเมื่อประสิทธิภาพเป็นเรื่องสำคัญ การเข้าใจสิ่งที่ ORM สร้าง query ออกมาจะช่วยให้ optimize ได้ถูกจุด”

Gemini (Google)


📚 References

  1. Fowler, M. (2002). Patterns of Enterprise Application Architecture
  2. Prisma. (2024). What is an ORM?
  3. SQLAlchemy. (2024). SQLAlchemy Documentation

🔗 กลับไปหน้าหลัก → sximi.github.io