6.1 แบบสอบถามที่มีชื่อ
Hibernate ช่วยให้คุณไม่เก็บแบบสอบถามโดยตรงในโค้ด เขาแนะนำให้ตั้งชื่อคิวรีและจัดเก็บแยกกันเป็นคำอธิบายประกอบ จากนั้นรับคำขอที่ต้องการโดยตรงโดยใช้ชื่อ ตัวอย่าง:
@org.hibernate.annotations.NamedQueries({
@org.hibernate.annotations.NamedQuery(name = "Employee_FindById",
query = "from Employee where id = :id"),
@org.hibernate.annotations.NamedQuery(name = "Employee_FindAllEmployes",
query = "from Employee"),
@org.hibernate.annotations.NamedQuery(name = "Employee_UpdateEmployeeName",
query = "Update Employee set name = :newName where id = :id"),
...
})
สามารถเพิ่มคำอธิบายประกอบก่อนคลาสเอนทิตีใดๆ ได้: ชื่อคิวรีจะไม่เชื่อมโยงกับเอนทิตีใดๆ
คุณยังสามารถเพิ่มพารามิเตอร์ต่างๆ ให้กับแบบสอบถาม (แบบสอบถาม):
@org.hibernate.annotations.NamedQuery(
name = "Employee_ FindAllEmployes",
query = "from Employee",
timeout = 1,
fetchSize = 10,
cacheable = true,
cacheMode = "GET"
)
การใช้คำขอนั้นง่ายมาก - คุณต้องใช้วิธีการcreateNamedQuery
แทนวิธีการcreateQuery
:
Query<Employee> query = session.createNamedQuery("Employee_FindAllEmployes", Employee.class);
List<Employee> resultLIst = query.list();
6.2 NativeQuery
และอีกอย่างที่เรียบง่ายแต่มีประโยชน์มากคือNativeQuery
หากคุณไม่ต้องการใช้ HQL แต่ต้องการใช้ Hibernate สำหรับการแมปเอนทิตี คุณสามารถเขียนแบบสอบถามใน SQL แบบเก่าที่ดีได้ ไม่มีใครจำกัดคุณ
ในการทำเช่น นี้คุณเพียงแค่เรียก method createNativeQuery()
แทนcreateQuery()
NativeQuery<Employee> query = session.createNativeQuery("select * from employee", Employee.class);
List<Employee> resultLIst = query.list();
คุณเพียงแค่เขียนcreateNativeQuery
และทุกอย่างจะทำงานเหมือนเดิม เมธอดนี้ส่งคืนวัตถุประเภทNativeQueryซึ่งรองรับเมธอดทั้งหมดที่ คลาส Queryรองรับ จะไม่มีอะไรเปลี่ยนแปลงสำหรับคุณ
นอกจากนี้ยังสามารถจัดเก็บNative SQL Queryเป็นNamed Query
@org.hibernate.annotations.NamedNativeQueries(
@org.hibernate.annotations.NamedNativeQuery(name = "Employee_GetAll",
query = "select * from employee",
resultClass = Employee.class)
)
และแน่นอน นี่คือรหัสสำหรับการทำงานกับพวกเขา:
NativeQuery<Employee> query = session.createNamedQuery("Employee_GetAll", Employee.class);
List<Employee> resultLIst = query.list();
GO TO FULL VERSION