在spring中配置hibernate

1.配置数据源:
    <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName">
   <value>com.mysql.jdbc.Driver</value>
  </property>
  <property name="url">
   <value>jdbc:mysql://192.168.19.2:3306/TimeSheet?useUnicode=true&amp;characterEncoding=UTF-8</value>
  </property>
  <property name="username">
   <value>用户名</value>
  </property>
  <property name="password">
   <value>密码</value>
  </property>
 </bean>
2.配置Hibernate的工厂类
    <!-- Hibernate SessionFactory Definition -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="mappingResources">
            <list>
                <!--在此添加O-R映射文件 -->
                <value>
                    com/zhifu/tm/model/bussiness/bdm/User.hbm.xml
                </value>               
            </list>
        </property>

       <!-- 在此配置Hibernate的一些属性-->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.cglib.use_reflection_optimizer">
                    true
                </prop>
                <prop key="hibernate.jdbc.bach_size">0</prop>
            </props>
        </property>
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean>

3.配置Spring中的Hibernate模板

    <!-- Spring Data Access Exception Translator Defintion -->
 <bean id="jdbcExceptionTranslator"
  class="org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator">
  <property name="dataSource">
   <ref bean="dataSource" />
  </property>
 </bean>

 <!-- Hibernate Template Defintion -->
 <bean id="hibernateTemplate"
  class="org.springframework.orm.hibernate3.HibernateTemplate">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
  <property name="jdbcExceptionTranslator">
   <ref bean="jdbcExceptionTranslator" />
  </property>
 </bean>

4.定义所用的DAO类,该类要定义一个HibernateTemplate模板类的属性,然后用第3步配置的hibernate模板来初始化该属性
      下面定义了一个类com.zhifu.tm.model.dao.tse.impl.WeekProjetAllDaoImpl,
   其中该类有一个名为hibernateTemplate,类型为HibernateTemplate的属性
   <bean id="weekProjetAllDao"
        class="com.zhifu.tm.model.dao.tse.impl.WeekProjetAllDaoImpl">
        <property name="hibernateTemplate">
            <ref bean="hibernateTemplate" />
        </property>
    </bean>


5.在所定义的DAO类中,调用Hibernate模板来实现访问数据库
   略..........

你可能感兴趣的:(在spring中配置hibernate)