fetch="select",另外发送一条select语句抓取当前对象关联实体或集合。例如:<many-to-one name="classes" column="classesid" fetch="select"/>
例子代码如下:
Student.hbm.xml <hibernate-mapping> <class name="hibernate.Student" table="t_student"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <many-to-one name="classes" column="classesid" fetch="select"/> </class> </hibernate-mapping> Classes.hbm.xml <hibernate-mapping package="hibernate"> <class name="Classes" table="t_classes"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <set name="students" inverse="true" cascade="all" fetch="select"> <key column="classesid"/> <one-to-many class="Student"/> </set> </class> </hibernate-mapping> 测试代码: public class FechTest extends TestCase {
public void testFetch1() { Session session = null; try { session = HibernateUtils.getSession(); session.beginTransaction();
Student student = (Student)session.load(Student.class, 1); //发出一条sql查询学生 System.out.println("student.name=" + student.getName()); //发出一条sql查询班级 System.out.println("classes.name=" + student.getClasses().getName()); session.getTransaction().commit(); }catch(Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally { HibernateUtils.closeSession(session); } } public void testFetch2() { Session session = null; try { session = HibernateUtils.getSession(); session.beginTransaction(); Classes classes = (Classes)session.load(Classes.class, 1); //发出一条sql查询班级 System.out.println("classes.name=" + classes.getName()); //发出一条sql查询这个班级下学生 for (Iterator iter=classes.getStudents().iterator(); iter.hasNext();) { Student student = (Student)iter.next(); System.out.println("student.name=" + student.getName()); } session.getTransaction().commit(); }catch(Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally { HibernateUtils.closeSession(session); } } } |