Spring Hibernater

来源:互联网 发布:印巴分治原因知乎 编辑:程序博客网 时间:2024/06/15 00:11

     一 问题
1.hibernater.cfg.xml信息如何加载
2.hibernater entity映射文件加载
3.Spring 如何控制Transaction
4.对对象CRUD的操作
二 配置
1.定义DataSource           配置
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName">                          
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://localhost:3306/test?autoReconnect=true&amp;useUnicode=true&amp;                                         characterEncoding=utf-8&amp;mysqlEncoding=utf8
            </value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>test</value>
        </property>
    </bean>

2.定义sessionFactory        配置
  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref local="dataSource"/>
        </property>
        <property name="mappingResources">
            <list>
                <value>entity/User.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.use_sql_comments">true</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
            </props>
        </property>
    </bean>
备注:此节为配置Hibernate的SessionFactory所以用此方法时,就不需要Hibernate-config.xml
       
    3.定义transactionManager   配置
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

4.定义userDao            配置
<bean id="userDao" class="dao.UserDaoImp">
        <property name="sessionFactory">
            <ref local="sessionFactory" />
        </property>
</bean>

5.定义UserDaoProxy         配置   //与JDBC相同
<bean id="userDaoProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager">
            <ref local="transactionManager"/>
        </property>
        <property name="target">
            <ref local="userDao"/>
        </property>
        <property name="transactionAttributes">
            <props>
                <prop key="insert*">PROPAGATION_REQUIRED</prop>
                <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
            </props>
        </property>
    </bean>

原创粉丝点击