DEV Community

slumboy
slumboy

Posted on

5 3

JPA Code example (Ep.1)

เกริ่นไปเรื่อย


บทนี้อาจจะดูวุ่นวายนิดหน่อยครับ แต่ไม่ปัญหาที่เราจะติดอะไร เพราะบทนี้จะใช้พื้นฐาน ในการสร้าง สรา้ง

class
method
getter
setter

เราจะเริ่มต่อจากบทที่เเล้ว ที่เราเตรียมไว้นะครับ

สิ่งที่เราต้องสร้างไว้ มีตามนี้ครับ

Entity หรือ POJO 1 ตัวครับ คือตัวที่เอาไว้ทำการ map กับ table ใน Database

  • Employee.java

Service เอาไว้ทำเกี่ยวกับพวก create ,update ,find ,delete

  • CreateEmployee.java
  • DeleteEmployee.java
  • FindEmployee.java
  • UpdateEmployee.java

Persistence คือ เราจะเรียกให้เข้าง่าย ๆ วันมันคือไฟล์ที่เอาใช้ config สิ่งต่างๆ คล้ายๆไฟล์ poperties โดยปกติจะมีอยู่แล้วใน META-INF

  • Persistence.xml

จะได้หน้าตา ประมาณนี้

alt text


วิธีสร้าง

ความจริงเราสร้างตามที่ตัวเองถนัดได้เลยนะ แต่ถ้าเอาตามผม ก็ดูตัวอย่างตามด้านล่างนี้ครับ
1.สร้าง Pacakage ขึ้นมาก่อน

คลิกขวาที่ src -> new --> Package

alt text

2.ตั้งชื่อ package
ตัวอย่าง com.ชื่อโปรเจค.ชื่อสำหรับบอกการใช้งาน เป็น pattern ของผมเอง แต่มันไม่ได้ตายตัวนะ เราสามารถสร้างตามที่เราเข้าใจ ได้เลย มันก็จะได้น่าตาประมาณนี้
alt text


  1. สร้าง class คลิกขวาที่ ชื่อ package ที่เราสร้างไว้ -> new --> class alt text
สังเกตดู

Package : มันจะชี้ไปที่ๆเราสร้างไว้ เพื่อบอกว่า class ที่เรากำลังสร้างอยู่ตอนนี้จะอยู่ภายใต้ package นี้
Name : คือชื่อ class ที่เราจะตั้ง

alt text


4.เหลือ Package สำหรับ Service ละในนั้นก็จะมี 4 class ตามรูปภาพด้านล่างนี้ เราลองสร้างกันดูเองนะ
alt text

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

Jetbrains Survey

Calling all developers!

Participate in the Developer Ecosystem Survey 2025 and get the chance to win a MacBook Pro, an iPhone 16, or other exciting prizes. Contribute to our research on the development landscape.

Take the survey

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay