HQL and native SQL queries are represented with an instance of org.hibernate.Query.
This interface offers methods for
1 parameter binding,
2 result set handling,
3 the execution of the actual query.
接口Query 提供的3項功能
補充
HQl 語句操作的是對象,不是數據庫的表,並且支持多態 from 類名
如果 from Object 則查詢數據庫所有的表
You always obtain a Query using the current Session:
List cats = session.createQuery(
"from Cat as cat where cat.birthdate < ?").setDate(0, date).list();
List mothers = session.createQuery(
"select mother from Cat as cat join cat.mother as mother where cat.name = ?")
.setString(0, name).list();
參數綁定除了基本類型還可以是 自定義對象
List kittens = session.createQuery(
"from Cat as cat where cat.mother = ?").setEntity(0, pk).list();
Cat mother = (Cat) session.createQuery(
"select cat.mother from Cat as cat where cat = ?").setEntity(0, izi).uniqueResult();]]
(如果檢索出的記錄是多條的話,報錯)
Query mothersWithKittens = (Cat) session.createQuery(
"select mother from Cat as mother left join fetch mother.kittens");
Set uniqueMothers = new HashSet(mothersWithKittens.list());
A query is usually executed by invoking list(). The result of the query will be loaded completely into a collection in memory. Entity instances retrieved by a query are in a persistent state. The
uniqueResult() method offers a shortcut if you know your query will only return a single object.
Queries that make use of eager fetching of collections usually return duplicates of the root objects, but with their collections initialized. You can filter these duplicates through a Set.
0 7_傳智播客hibernate教程_實體類或屬性名與數據庫關鍵字衝突問題
解決:
1 修改數據庫表名和字段名
2 在配置文件 用 反引號 ·· 將table 和 column 的值引起來