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());
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。