我们希望在Spring和Hibernate方面使用HQL获取数据库中的所有记录

时间:2015-02-11 13:28:16

标签: spring hibernate

Here i tried 2 write cod 2 get list from Mysql Database using spring nd Hibernate.

但问题在于如何初始化** org.hibernate.Session se 通过" applicationContext.xml" bean类的文件....

public void getList(**Session se**){
    String liststudent="from StudentList stud";
    Query q=se.createQuery(liststudent);

    List<Object> list=q.list();
    for(Object obj:list){
        Object studarr[]=(Object[])obj;
        System.out.println("Data at Zero Index"+studarr[0]);
    }
}


As here property name **template** has been initialized by the ref template.
Is there any way to initialize Session se.


<bean name="mydao" class="dao.MyDao">
    <property name="template" ref="template"></property>

</bean>

1 个答案:

答案 0 :(得分:0)

使用context.xml文件

定义sessionFactory

<bean id="sessionFactory" class="LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--define other properties...mapping files
</bean>

定义hibernateTemplate

<bean id="template" class="*HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

然后

<bean name="mydao" class="dao.MyDao">
   <property name="template" ref="template"></property>
</bean>

注意:已经省略了类包