hibernate參數綁定

來源:互聯網
上載者:User

標籤:hibernate   參數綁定   

參數綁定有三種方法,在此講效率較高的,也就是常用的兩種方法:

持久化類:

package entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

//HQl查詢圖書資訊
@Entity
@Table
public class HqlQuery {
 private int id;
 private String name;
 private String author;
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getAuthor() {
  return author;
 }
 public void setAuthor(String author) {
  this.author = author;
 }
 
 public HqlQuery() {
  super();
 }
 public HqlQuery(String name, String author) {
  super();
  
  this.name = name;
  this.author = author;
 }
 
}

//參數綁定的查詢:

package test;

import java.util.Iterator;
import java.util.List;
import java.util.jar.Attributes.Name;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import entity.HqlQuery;

import util.HibernateUtil;

//參數綁定
public class ParamTest {

 public static void main(String[] args) {
  //parQue();
  named();
 }
 //使用預留位置
 public static void parQue(){
  Session session=HibernateUtil.getCurrentSession();
  Transaction transaction=session.beginTransaction();
  String hql="from HqlQuery where name=?";
  Query query=session.createQuery(hql);
  query.setParameter(0,"老人與海");//設定參數
  Iterator it=query.iterate();
  while(it.hasNext()){
   HqlQuery h=(HqlQuery)it.next();
   System.out.println(h.getAuthor());
  }
 }
 //使用具名引數
 public static void named(){
  Session session=HibernateUtil.getCurrentSession();
  Transaction transaction=session.beginTransaction();
  String hql="from HqlQuery where name=:name";
  Query query=session.createQuery(hql);
     query.setParameter("name","與狼共舞");
     Iterator it=query.iterate();
     while(it.hasNext()){
      HqlQuery h=(HqlQuery)it.next();
      System.out.println("" + h.getAuthor());
     }
 }
}

 

hibernate參數綁定

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.