1. JPQL的参数绑定
1.1 按参数名字绑定
在JPQL查询语句中定义命名参数,命名参数以“:”开头,形式如下:
TypedQuery<Customer> query=entityManager.createQuery(
"from Customer as c where c.name=:customerName "
+"and c.age=:customerAge",Customer.class);
以上JPQL查询语句定义了两个命名参数“customerName”和“customerAge”。接下来调用Query的setParameter()方法来绑定参数:
query.setParameter("customerName",name);
query.setParameter("customerAge",age);
Query的setParameter()方法能够绑定各种数据类型的命名参数。该方法的第一个参数代表命名参数的名字,第二个参数代表命名参数的值。
在SQL语句中,如果字符串中包含单引号,应该采用重复单引号的形式,例如:
update CUSTOMERS set NAME='''Tom' where ID=1;
以上update语句把NAME字段的值改为:'Tom
1.2 按参数位置绑定
在JPQL查询语句中用“?”来定义参数的位置,形式如下:
TypedQuery<Customer> query=entityManager.createQuery(
"from Customer as c where c.name=?1 &