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">