美文网首页
【Hibernate】session.createQuery的参

【Hibernate】session.createQuery的参

作者: f07bfe4a10fd | 来源:发表于2016-09-07 20:55 被阅读1728次

    参数绑定: 都支持位置绑定和命名绑定
    如: Java代码

    session.createQuery("from Person where id=:id").setInteger("id",1);   
    session.createQuery("from Person where id=?").setInteger(0,1);  
    

    **基本的参数绑定: **
    setString();
    setInteger();
    等...
    **特殊的参数绑定 **

    1. 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);  
    
    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.DATEHibernate.TIMESTAMP,因此必须在setParameter()方法中显式指定到底对应哪种Hibernate映射类型,如:

    Query query = session.createQuery("from Customer c where c.birthday=:birthday");   
    query.setParameter("birthday",birthday,Hibernate.DATE);  
    
    1. 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是安全的.

    相关文章

      网友评论

          本文标题:【Hibernate】session.createQuery的参

          本文链接:https://www.haomeiwen.com/subject/edtsettx.html