学习了一段hibernate,综合一下网上查到的资料,下面是总理一下hibernate对数据库的操作方式。
检索方式:
1、导航对象图检索方式。通过已经加载的对象,调用.iterator()方法可以得到order对象
如果是首次执行此方法,Hib会从数据库加载关联的order对象,否则就从缓存中得到
2、OID检索方式。通过session的get,load方法知道了OID的情况下可以使用
3、HQL检索方式。使用面向对象的HQL查询语句session的find方法利用HQL来查询
4、QBC检索方式。利用QBC API来检索它是封装了基于字符串的查询语句
5、本地的SQL检索方式。使用本地数据库的SQL查询语句Hib会负责把检索到的JDBC结果集映射为持久化对象图
五种检索方式的使用场合和特点:
HQL : 是面向对象的查询语言,同SQL有些相似是Hib中最常用的方式。
查询设定各种查询条件。
支持投影查询,检索出对象的部分属性。
支持分页查询,允许使用having和group by
提供内制的聚集函数,sum(),min(),max()
能调用用户的自定义SQL
支持子查询,嵌入式查询
支持动态绑定参数
建议使用Query接口替换session的find方法。
示例:
Query Q = session.createQuery("from customer as c where c.name = :customerName" + "and c.age = :customerAge");
query.setString ("customerName" , "tom");
query.setInteger("customerAge" , "21");
list result = query.list();
HQL语句的参数绑定Query接口提供了绑定各种Hib映射类型的方法:
setBinary()
setString()
setBoolean()
setByte()
setCalendar()
setCharacter()
setDate()
setDouble()
setText()
setTime()
setTimestamp()
setEntity() //把参数与一个持久化类的事例绑定
示例: lsit result = session.createQuery("from order o where o.customer = :customer").setEntity("customer" , customer).list() ;
setParameter()//绑定任意类型的参数
setProperties()//把命名参数与一个对象的属性值绑定
示例:Query query = session.createQuery("from customer c where c.name = :name " + "and c.age =:age" );
Query.setProperties(customer);
QBC : QBCAPI提供了另一种方式,主要是Criteria接口、Criterion接口和Expression类
示例:查询customer对应表中name以‘t’开头,age等于21的值
Criteria criteria = session.createCriteria(customer.class);
Criterion criterion1 = Expression.like("name","t%");
Criterion criterion2 = Expression.eq("age",new Integer(21));
Critera = criteria.add(criterion1) ;
Critera = criteria.add(criterion2) ;
list result = criteria.list();
或是: list result = session.createCriteria(Customer.class).add(Expression.eq("this.name","tom")).list();//写在了一起
NHibernate.Criterion方法解释
HQL运算符 | QBC运算符 | 含义 |
= | Restrictions.eq() | 等于equal |
<> | Restrictions.ne() | 不等于not equal |
> | Restrictions.gt() | 大于greater than |
>= | Restrictions.ge() | 大于等于greater than or equal |
< | Restrictions.lt() | 小于less than |
<= | Restrictions.le() | 小于等于less than or equal |
is null | Restrictions.isnull() | 等于空值 |
is not null | Restrictions.isNotNull() | 非空值 |
like | Restrictions.like() | 字符串模式匹配 |
and | Restrictions.and() | 逻辑与 |
and | Restrictions.conjunction() | 逻辑与 |
or | Restrictions.or() | 逻辑或 |
or | Restrictions.disjunction() | 逻辑或 |
not | Restrictions.not() | 逻辑非 |
in(列表) | Restrictions.in() | 等于列表中的某一个值 |
not in(列表) | Restrictions.not(Restrictions.in()) | 不等于列表中任意一个值 |
between x and y | Restrictions.between() | 闭区间xy中的任意值 |
not between x and y | Restrictions.not(Restrictions..between()) | 小于值X或者大于值y |