D、 setProperties()方法:(setEntity())
在Hibernate中可以使用setProperties()方法,将命名参数与一个对象的属性值绑定在一起,如下程序代码:
Customer customer=new Customer();
customer.setName(“pansl”);
customer.setAge(80);
Query query=session.createQuery(“from Customer c where c.name=:name and c.age=:age ”);
query.setProperties(customer);
setProperties()方法会自动将customer对象实例的属性值匹配到命名参数上,但是要求命名参数名称必须要与实体对象相应的属性同名。
这里还有一个特殊的setEntity()方法,它会把命名参数与一个持久化对象相关联,如下面代码所示:
Customer customer=(Customer)session.load(Customer.class,”1”);
Query query=session.createQuery(“from Order order where order.customer=:customer ”);
query. setEntity(“customer”,customer);
List list=query.list();
上面的代码会生成类似如下的SQL语句:
Select * from order where customer_ID=’1’;
package com.haha.test;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import com.haha.dao.HibernateSessionFactory;
import com.haha.info.Books;
public class Test1 {
public static void main(String[] args) {
BookWhere1 bk=new BookWhere1();
bk.setId(5000);
bk.setName("java%");
Query qq=HibernateSessionFactory.getSession()
.createQuery("from Books where id>:id and title like :name");
qq.setProperties(bk);
List<Books> list=qq.list();
for(Books b:list){
System.out.println(b.getId()+","+b.getTitle());
}
}
}