Hibernate的三种常用检索方式
Hibernate 提供了以下几种检索对象的方式
¨ 导航对象图检索方式: 根据已经加载的对象导航到其他对象
¨ OID 检索方式: 按照对象的 OID 来检索对象
¨ HQL 检索方式: 使用面向对象的 HQL 查询语言
¨ QBC 检索方式: 使用 QBC(Query By Criteria) API 来检索对象. 这种 API 封装了基于字符串形式的查询语句, 提供了更加面向对象的查询接口.
¨ 本地 SQL 检索方式: 使用本地数据库的 SQL 查询语句
一、HQL
public class HQLTest {
@Test
public void test1(){
//获取session对象
Session session =HiberSessionFactory.getSession();
Class clazz = Admin.class;
//hql查询 from 类名
Query query = session.createQuery("from "+clazz.getName());
//获取结果
List<Admin> admins =query.list();
for(Admin admin:admins){
System.out.println(admin.getName());
}
HiberSessionFactory.closeSession();
}
@Test
public void test2(){
//获取session对象
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
//获取结果
List<Admin> admins =session.createQuery("from Admin").list();
for(Admin admin:admins){
System.out.println(admin.getName());
}
HiberSessionFactory.closeSession();
}
@Test
public void test3(){
//获取session对象s
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
//获取结果 name=? 位置从0开始
Admin admin= (Admin) session.createQuery("from Admin admin where admin.name=?").setString(0, "junjun10").uniqueResult();
System.out.println(admin.getName());
HiberSessionFactory.closeSession();
}
@Test
public void test4(){
//获取session对象s
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
//获取结果 name=:names names
Admin admin= (Admin) session.createQuery("from Admin admin where admin.name=:names").setString("names", "junjun10").uniqueResult();
System.out.println(admin.getName());
HiberSessionFactory.closeSession();
}
@Test
public void test5(){
//获取session对象
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
//获取结果
List<Admin> admins =session.createQuery("from Admin admin order by admin.id desc").list();
for(Admin admin:admins){
System.out.println(admin.getName());
}
HiberSessionFactory.closeSession();
}
@Test
public void test6(){
//获取session对象
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
//setFirstResult(开始位置).setMaxResult(每页显示的数量);
//获取结果
//List<Admin> admins =session.createQuery("from Admin admin order by admin.id desc").setFirstResult(0).setMaxResults(3).list();
List<Adver> advers = session.createQuery("from Adver adver where adver.flag=:flag order by id desc").setInteger("flag", 1).setFirstResult(0).setMaxResults(4).list();
for(Adver adver:advers){
System.out.println(adver.getId());
}
/* for(Admin admin:admins){
System.out.println(admin.getName());
}
*/
HiberSessionFactory.closeSession();
}
@Test
public void test7(){
//获取session对象
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
//setFirstResult(开始位置).setMaxResult(每页显示的数量);
//获取结果
List list =session.createQuery("select admin.name,admin.pass from Admin admin order by admin.id desc").setFirstResult(0).setMaxResults(3).list();
Iterator it = list.iterator();
while(it.hasNext()){
Object obj[]=(Object[]) it.next();
System.out.println(obj[0]);
}
HiberSessionFactory.closeSession();
}
@Test
public void test8(){
//获取session对象
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
//setFirstResult(开始位置).setMaxResult(每页显示的数量);
//获取结果
List list =session.createQuery("select admin.name from Admin admin order by admin.id desc").setFirstResult(0).setMaxResults(3).list();
Iterator it = list.iterator();
while(it.hasNext()){
String name=(String) it.next();
System.out.println("--"+name);
}
HiberSessionFactory.closeSession();
}
@Test
public void test9(){
//获取session对象
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
//setFirstResult(开始位置).setMaxResult(每页显示的数量);
//获取结果
List<Admin> admins =session.createQuery("select new hjds.domain.privilege.Admin(admin.name,admin.pass) from Admin admin order by admin.id desc").setFirstResult(0).setMaxResults(3).list();
for(Admin admin:admins){
System.out.println(admin.getName());
}
HiberSessionFactory.closeSession();
}
@Test
public void test10(){
//获取session对象
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
Class clazz = Admin.class;
//setFirstResult(开始位置).setMaxResult(每页显示的数量);
//获取结果
long count =(Long) session.createQuery("select count(c) from "+clazz.getName()+" c").uniqueResult();
System.out.println(count);
HiberSessionFactory.closeSession();
}
@Test
public void test11(){
//获取session对象
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
//setFirstResult(开始位置).setMaxResult(每页显示的数量);
//获取结果
int count =session.createQuery("from Admin").list().size();
System.out.println(count);
HiberSessionFactory.closeSession();
}
@Test
public void test12(){
//获取session对象
Session session =HiberSessionFactory.getSession();
//hql查询 from 类名
//setFirstResult(开始位置).setMaxResult(每页显示的数量);
//获取结果
Admin admin =(Admin) session.getNamedQuery("findAdminByName").setString("name", "junjun10").uniqueResult();
System.out.println(admin.getPass());
HiberSessionFactory.closeSession();
}
@Test
public void test13(){
//获取session对象
Session session =HiberSessionFactory.getSession();
Transaction ts = session.beginTransaction();
//hql查询 from 类名
//setFirstResult(开始位置).setMaxResult(每页显示的数量);
String delete="delete from Admin a where a.id=:id";
//获取结果
int num=session.createQuery(delete).setInteger("id", 2).executeUpdate();
System.out.println(num);
ts.commit();
HiberSessionFactory.closeSession();
}
}
二、QBC
public class QBCTest {
@Test
public void test1(){
Session session =HiberSessionFactory.getSession();
//
Criteria criteria =session.createCriteria(Admin.class);
List<Admin> admin =criteria.list();
for(Admin adm:admin){
System.out.println(adm.getName());
}
HiberSessionFactory.closeSession();
}
@Test
public void test2(){
Session session =HiberSessionFactory.getSession();
//
List<Admin> admin =session.createCriteria(Admin.class).list();
for(Admin adm:admin){
System.out.println(adm.getName());
}
HiberSessionFactory.closeSession();
}
@Test
public void test3(){
Session session =HiberSessionFactory.getSession();
//
Admin admin =(Admin) session.createCriteria(Admin.class).add(Restrictions.eq("name", "junjun10")).uniqueResult();
System.out.println(admin.getName());
HiberSessionFactory.closeSession();
}
@Test
public void test4(){
Session session =HiberSessionFactory.getSession();
//
List<Admin> admin=session.createCriteria(Admin.class).setFirstResult(0).setMaxResults(3).list();
for(Admin adm:admin){
System.out.println(adm.getName());
}
HiberSessionFactory.closeSession();
}
@Test
public void test5(){
Session session =HiberSessionFactory.getSession();
//
List<Admin> admin=session.createCriteria(Admin.class).setFirstResult(0).setMaxResults(3).addOrder(Order.desc("id")).list();
for(Admin adm:admin){
System.out.println(adm.getName());
}
HiberSessionFactory.closeSession();
}
@Test
public void test6(){
Session session =HiberSessionFactory.getSession();
//
List<Admin> admin=session.createSQLQuery("select id,name,pass from admin").addEntity(Admin.class).list();
for(Admin adm:admin){
System.out.println(adm.getName());
}
HiberSessionFactory.closeSession();
}
@Test
public void test7(){
Session session =HiberSessionFactory.getSession();
//
Admin admin=(Admin) session.createSQLQuery("select id,name,pass from admin where id=?").addEntity(Admin.class).setInteger(0, 1).uniqueResult();
System.out.println(admin.getName());
HiberSessionFactory.closeSession();
}
}
三、本地SQL(略)
在进行ssh(Hibernate4)整合时遇到的有关数据库操作的问题:
我写了这么一个方法:
@Override
public List<SiteLines> getObjectsByLine(final Integer lid) {
return hibernateTemplate.execute(new HibernateCallback<List<SiteLines>>() {
@Override
public List<SiteLines> doInHibernate(Session session) throws HibernateException {
return session.createQuery(" from SiteLines s where s.line.id=? order by orders asc").setInteger(0, lid).list();
}
});
}
测试时遇到以下问题:
/*
java.lang.ClassCastException: com.buslines.domain.Lines_$$_javassist_0 cannot be cast to javassist.util.proxy.Proxy
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.getProxy(JavassistLazyInitializer.java:147)
at org.hibernate.proxy.pojo.javassist.JavassistProxyFactory.getProxy(JavassistProxyFactory.java:75)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.createProxy(AbstractEntityTuplizer.java:771)
at org.hibernate.persister.entity.AbstractEntityPersister.createProxy(AbstractEntityPersister.java:4613)
at org.hibernate.event.internal.DefaultLoadEventListener.createProxyIfNecessary(DefaultLoadEventListener.java:350)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:271)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:151)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1106)
at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1025)
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:716)
at org.hibernate.type.EntityType.resolve(EntityType.java:502)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:170)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:144)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1115)
at org.hibernate.loader.Loader.processResultSet(Loader.java:973)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doList(Loader.java:2554)
at org.hibernate.loader.Loader.doList(Loader.java:2540)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
at org.hibernate.loader.Loader.list(Loader.java:2365)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:497)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:236)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1300)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
at com.buslines.dao.impl.SiteLinesDaoImpl$2.doInHibernate(SiteLinesDaoImpl.java:52)
at com.buslines.dao.impl.SiteLinesDaoImpl$2.doInHibernate(SiteLinesDaoImpl.java:1)
at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
at org.springframework.orm.hibernate4.HibernateTemplate.execute(HibernateTemplate.java:295)
at com.buslines.dao.impl.SiteLinesDaoImpl.getObjectsByLine(SiteLinesDaoImpl.java:48)
at com.buslines.service.impl.SiteLinesServiceImpl.getObjectsByLine(SiteLinesServiceImpl.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy15.getObjectsByLine(Unknown Source)
at ssh.test.SiteLinesTest.testgetObjectsByLine(SiteLinesTest.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
*/
采用本地SQL语句写仍是一样的问题。
与延迟加载有关,解决办法:
在映射文件的class加上lazy="false"的属性,如:
<class name="Site" table="site" catalog="spring" lazy="false">
Hibernate的三种常用检索方式的更多相关文章
- Hibernate基础学习(七)—检索方式
一.概述 Hibernate有五种检索方式. 1.导航对象图检索方式 根据已经加载的对象,导航到其他对象. Order order = (Order)session.get(Ord ...
- Hibernate —— HQL、QBC检索方式
一.HQL 检索方式 以双向的一对多来测试 HQL 检索方式.以 Department 和 Employee 为例. 建表语句: CREATE TABLE department ( dept_id ) ...
- java框架之Hibernate(4)-几种检索方式
准备 模型及映射文件 package com.zze.bean; import java.util.HashSet; import java.util.Set; public class Class ...
- 总结hibernate框架的常用检索方式
1.hibernate框架的检索方式有以下几种: OID检索:根据唯一标识OID检索数据 对象导航检索:根据某个对象导航查询与该对象关联的对象数据 HQL检索:通过query接口对象查询 QBC检索: ...
- hibernate检索方式(HQL 检索方式,QBC 检索方式,本地 SQL 检索方式)
hibernate有五种检索方式,这儿用 单向的一对多的映射关系 例子,这儿有后三种的方式: 导航对象图检索方式: 根据已经加载的对象导航到其他对象 OID 检索方式: 按照对象的 OID 来检索对象 ...
- Hibernate 检索方式
概述 •Hibernate 提供了以下几种检索对象的方式 –导航对象图检索方式: 根据已经加载的对象导航到其他对象 –OID 检索方式: 按照对象的 OID 来检索对象 –HQL 检索方式: 使用 ...
- [原创]java WEB学习笔记89:Hibernate学习之路-- -Hibernate检索方式(5种),HQL介绍,实现功能,实现步骤,
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- Hibernate检索方式 分类: SSH框架 2015-07-10 22:10 4人阅读 评论(0) 收藏
我们在项目应用中对数据进行最多的操作就是查询,数据的查询在所有ORM框架中也占有极其重要的地位.那么,如何利用Hibernate查询数据呢?Hibernate为我们提供了多种数据查询的方式,又称为Hi ...
- Hibernate 检索方式之 HQL 检索方式
HQL(Hibernate Query Language) 是面向对象的查询语言,它和 SQL 查询语言有些相似.在 Hibernate 提供的各种检索方式中,HQL 是使用最广的一种检索方式,它有如 ...
随机推荐
- Cisco IOS basic system management command reference
absolute : to specify an absolute time for a time-range (in time-range configuration mode) no absolu ...
- 利用ps指令查看某个程序的进程状态
ps -ef是查看所有的进程,然后用grep筛选出你要的信息. eg.
- 打饭助手之NABC
Need: 同学们在早上跑操后要吃早饭,还有中午打饭时人更是多.常常要排很长的队伍,造成时间的浪费,和焦急的等待.因此我们需要错开打饭的高峰期,来避免打饭排队的悲哀. Approach: 通过获取摄像 ...
- hql语句理解2
/* * this.getSession().createQuery("sdfdf").executeUpdate();这里面的query可以是delete,update,inse ...
- MongoDB 语法(转)
Mongod.exe 是用来连接到mongo数据库服务器的,即服务器端. Mongo.exe 是用来启动MongoDB shell的,即客户端. 其他文件: mongodump 逻辑备份工具. mon ...
- dllimport路径问题
今天做了个试验,是针对dllimport("XXX.DLL");这样写的时候,系统是如何寻找该dll的. 首先系统会搜寻主应用程序根目录. 其次搜寻操作系统安装目录,一般情况是C: ...
- pod创建的工程找不到库
ld: library not found for -lAFNetworking app工程 和 Pod工程里面的所有库 Build Active Architecuture Only 所有库都设 ...
- (转)iOS消息推送机制的实现
原:http://www.cnblogs.com/qq78292959/archive/2012/07/16/2593651.html iOS消息推送机制的实现 iOS消息推送的工作机制可以简单的用下 ...
- hdu 2071
Ps:输出n个数里最大的 #include "stdio.h" int main(){ ],max; int i,j,n,t; while(~scanf("%d" ...
- error C3163: “_vsnprintf”: 属性与以前的声明不一致
这是在vs2008中遇到的错误,vs2008以前没有,vs2008以后的vs也没有. c:\program files\microsoft visual studio 9.0\vc\include\s ...