使用inner join子句可以实现内连接,只要两个持久化类对应的两个表的关联字段之间有相符的值,内连接将组合两个表中的连接。内连接在一对多(多对一)的关联中是最常见的一连接。如:
String hql = "select p from Product p inner join p.category";
Query query = session.createQuery(hql);
List<Product> list = query.list();
/**
* 测试使用内连接
*/
public void testUseInnerJoin(){
Session session = null;
session = HibernateUtils.getCurrentSession();
String hql = "select p from Product p inner join p.category";
Query query = session.createQuery(hql);
List<Product> list = query.list();
HibernateUtils.closeSession(session);
for(Product obj : list){
System.out.println(obj.toString());
}
}
这里注意的是要在多一方设置lazy=”false”属性,否则在显示查询结果会抛出迟延加载的异常:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
at com.kkoolerter.hibernate.beans.Category$$EnhancerByCGLIB$$228a9fa6.toString(<generated>)
at com.kkoolerter.hibernate.beans.Product.toString(Product.java:67)
at HQLTest.testUseInnerJoin(HQLTest.java:144)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at junit.framework.TestCase.runTest(TestCase.java:164)
at junit.framework.TestCase.runBare(TestCase.java:130)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:120)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
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)