2017年4月2日 星期日

Hibernate Query 用法

Hibernate Query examples (HQL)
出處: mkyong.com
         
https://www.mkyong.com/hibernate/hibernate-query-examples-hql/

 HQL Select Query Example

Retrieve a stock data where stock code is “7277”.
Query query = session.createQuery("from Stock where stockCode = :code ");
query.setParameter("code", "7277");
List list = query.list();
Query query = session.createQuery("from Stock where stockCode = '7277' ");
List list = query.list();

2. HQL Update Query Example

Update a stock name to “DIALOG1” where stock code is “7277”.
Query query = session.createQuery("update Stock set stockName = :stockName" +
        " where stockCode = :stockCode");
query.setParameter("stockName", "DIALOG1");
query.setParameter("stockCode", "7277");
int result = query.executeUpdate();
Query query = session.createQuery("update Stock set stockName = 'DIALOG2'" +
        " where stockCode = '7277'");
int result = query.executeUpdate();

3. HQL Delete Query Example

Delete a stock where stock code is “7277”.
Query query = session.createQuery("delete Stock where stockCode = :stockCode");
query.setParameter("stockCode", "7277");
int result = query.executeUpdate();
Query query = session.createQuery("delete Stock where stockCode = '7277'");
int result = query.executeUpdate();

4. HQL Insert Query Example

In HQL, only the INSERT INTO … SELECT … is supported; there is no INSERT INTO … VALUES. HQL only support insert from another table. For example
"insert into Object (id, name) select oo.id, oo.name from OtherObject oo";
Insert a stock record from another backup_stock table. This can also called bulk-insert statement.
Query query = session.createQuery("insert into Stock(stock_code, stock_name)" +
       "select stock_code, stock_name from backup_stock");
int result = query.executeUpdate();
The query.executeUpdate() will return how many number of record has been inserted, updated or deleted.

Reference

  1. Hibernate 3.3.2 query documentation

沒有留言:

Java 不同編碼字串, 其字串長度大小計算

以 Java 開發專案, 在 DAO 寫入資料庫時, 常遇到JAVA 字串與資料庫編碼不一致, 有時會產生字串過長,導致無法寫入資料庫的情況. 這時就要在入庫前, 先驗證 JAVA 編碼字串是否超出資料庫欄位長度 JAVA 依 不同編碼, 其長度是不一樣的 如: ...