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 是使用最广的一种检索方式,它有如 ...
随机推荐
- 关于java.lang.reflect.InvocationTargetException
今天遇到java.lang.reflect.InvocationTargetException错误,卡了好一会儿,报错代码 try { Class<?> c= Class.forName( ...
- 经典线程同步 信号量Semaphore
阅读本篇之前推荐阅读以下姊妹篇: <秒杀多线程第四篇一个经典的多线程同步问题> <秒杀多线程第五篇经典线程同步关键段CS> <秒杀多线程第六篇经典线程同步事件Event& ...
- 解决python version 2.7 required,which was not find in the registry
程序自动写注册表 http://www.vvivv.com/post-143.html 手工写 http://blog.csdn.net/baikaishui525/article/details/9 ...
- python遍历文件夹下的文件
在读文件的时候往往需要遍历文件夹,python的os.path包含了很多文件.文件夹操作的方法.下面列出: os.path.abspath(path) #返回绝对路径 os.path.basename ...
- iOS应用崩溃日志分析
转自raywenderlich 作为一名应用开发者,你是否有过如下经历? 为确保你的应用正确无误,在将其提交到应用商店之前,你必定进行了大量的测试工作.它在你的设备上也运行得很好,但是,上了应 ...
- poj1160 dp
//Accepted 564 KB 63 ms //和hdu1227一样 //dp[i][j]=min(dp[i][j],dp[k][j-1]+cost[k+1][i]) //初始化条件,dp[0][ ...
- Java中线程的锁和数据库中的事务隔离级别
当涉及到两个或多个线程操作同一个资源时,就会出现锁的问题. 数据库中的某一条记录或者是某一个对象中的字段,可以修改,也可以读取,一般情况下,读取的那个方法应该加锁(即用synchronized互斥), ...
- (spring-第16回【AOP基础篇】)基本概念
AOP(Aspect Oriented Programing),面向切面方程.介绍具体定义前,先看一个例子: package com.baobaotao.concept; public class F ...
- flex css 布局
http://www.w3cplus.com/css3/flexbox-basics.html
- 正确的SVN导入代码命令
sudo svn import -m "" /media/yang/10/ubuntuFiles/svnAbout/mypro/ svn://127.0.0.1/mypro/