6.1 Jeneng Pitakonan
Hibernate ngidini sampeyan ora nyimpen pitakon langsung ing kode kasebut. Nanging, dheweke nyaranake menehi jeneng pitakon lan simpen kanthi kapisah minangka anotasi. Inggih, banjur njupuk panjalukan sing dipengini langsung kanthi jeneng. Tuladha:
@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"),
...
})
Anotasi bisa ditambahake sadurunge kelas Entitas: jeneng pitakon ora ana gandhengane karo Entitas.
Sampeyan uga bisa nambah macem-macem paramèter menyang pitakon (query):
@org.hibernate.annotations.NamedQuery(
name = "Employee_ FindAllEmployes",
query = "from Employee",
timeout = 1,
fetchSize = 10,
cacheable = true,
cacheMode = "GET"
)
Nggunakake panjaluk kasebut gampang banget - kanggo iki sampeyan kudu nggunakake metode createNamedQuery
tinimbang metode createQuery
:
Query<Employee> query = session.createNamedQuery("Employee_FindAllEmployes", Employee.class);
List<Employee> resultLIst = query.list();
6.2 NativeQuery
Lan liyane prasaja nanging migunani banget NativeQuery .
Yen sampeyan ora pengin nggunakake HQL, nanging pengin nggunakake Hibernate kanggo pemetaan entitas, sampeyan bisa nulis pitakon ing SQL lawas sing apik. Ora ana sing mbatesi sampeyan.
Kanggo nindakake iki, sampeyan mung kudu nelpon cara createNativeQuery()
, tinimbang createQuery()
.
NativeQuery<Employee> query = session.createNativeQuery("select * from employee", Employee.class);
List<Employee> resultLIst = query.list();
Sampeyan mung nulis createNativeQuery
lan kabeh bakal bisa digunakake kaya sadurunge. Cara iki ngasilake obyek saka jinis NativeQuery , sing ndhukung kabeh metode sing didhukung kelas Query . Ora ana sing bakal ngganti sampeyan.
Kajaba iku, Native SQL Query uga bisa disimpen minangka Named Queries .
@org.hibernate.annotations.NamedNativeQueries(
@org.hibernate.annotations.NamedNativeQuery(name = "Employee_GetAll",
query = "select * from employee",
resultClass = Employee.class)
)
Lan mesthi, iki kode kanggo nggarap dheweke:
NativeQuery<Employee> query = session.createNamedQuery("Employee_GetAll", Employee.class);
List<Employee> resultLIst = query.list();