参数绑定: 都支持位置绑定和命名绑定
如: Java代码
session.createQuery("from Person where id=:id").setInteger("id",1);
session.createQuery("from Person where id=?").setInteger(0,1);
**基本的参数绑定: **
setString();
setInteger();
等...
**特殊的参数绑定 **
setEntity()
Customer customer = new Customer();
customer.setId(1);
session.createQuery("from Order o where o.customer =:customer ").setEntity("customer", customer);
等价于
session.createQuery("from Order o where o.customer.id =:customerid ").setInteger("customerid", 1);
setParameter()
Query query = session.createQuery("from Order o where o.customer=:customer and o.orderNumber like :orderNumber");
query.setParameter("customer", customer, Hibernate.entity(Customer.class));
对于某些参数,Hibernate能跟根据参数值的Java类型推断出对应的映射类型,此时不需要在setParameter()
方法中显式指定映射类型,如:
Query query = session.createQuery("from Order o where o.customer=:customer and o.orderNumber like :orderNumber");
query.setParameter("customer", customer);
query.setParameter("orderNumber", orderNumber);
对于日期类型,如java.util.Date
类型,会对应多种Hibernate映射类型,如Hibernate.DATE
或Hibernate.TIMESTAMP
,因此必须在setParameter()
方法中显式指定到底对应哪种Hibernate映射类型,如:
Query query = session.createQuery("from Customer c where c.birthday=:birthday");
query.setParameter("birthday",birthday,Hibernate.DATE);
-
setProperties()
方法:用于把命名参数与一个对象的属性值绑定,如:
Customer customer = new Customer();
customer.setName("Tom");
customer.setAge(21);
Query query = session.createQuery("from Customer as c where c.name=:name and c.age="age");
query.setProperties(customer);
setProperties()
调用setParameter()
方法,setParameter()
方法再根据Customer
对象的属性的Java类型来推断Hibernate映射类型.如果命名参数为日期类型,不能通过setProperties()
方法来绑定.
参数绑定对null
是安全的.
网友评论