DEV Community

slumboy
slumboy

Posted on

4 2

พื้นฐาน JPA

หลักการสร้าง Entity Class


  1. เป็น java class ตั้งชื่อว่าอะไรก็ได้ (ให้สื่อกับความหมายนั้นๆ)
  2. implements Serializable
  3. มี annotation @Entiry อยู่บน class
  4. Entity Class ต้องมี default constructor ที่ไม่มี parameter เท่านั้น เช่น

    public Category(){ }
    
  5. ในกรณีที่ต้องการกำหนดค่าบางอย่างของ Table ให้ใช้ annotation @Table เช่น

    • การกำหนดชื่อให้ table จะใช้ attribute name
    • แต่ถ้าไม่ได้กำหนดชื่อ default table name จะเป็นชื่อของ entity class นั้นๆ
    • การตั้งชื่อ table ให้ระวังเรื่อง reserve word ของ database แต่ละเจ้า
  6. กำหนด attribute จะต้องมี attribute อย่างน้อย 1 attribute ที่มี annotation @Id เพื่อบอกว่าเป็น primary key

  7. มี method getter และ setter เพื่อ get และ set ค่าให้กับแต่ละ attribute

  8. ในการกำหนดค่า แต่ละ attribute หรือแต่ละ column ให้ใช้ annotation @Colum อยู่บน attribute นั้นๆ

  9. การ map relationship ให้สร้าง attribute ที่มี data type เป็น Entity Class ที่ต้องการ map ด้วย จากนั้นก็ใส่ annotation Mapping ต่างๆ ไว้บน attribute นั้นๆ เช่น

    @OneToOne
    @OneToMany
    @ManyToOne
    @ManyToMany
    

หลักการคร่าวๆ มีประมาณนี้

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay