在導入hibernate包之前要注意先進入Myeclipse database explorer中創建數據庫連接,注意建立數據庫連接的驅動包的位置(最好是MyEclipse工程意外位置的包)
因爲整合了spring,所以hibernate的配置文件就不用創建了,sessionFactory也無需創建,如下圖:
ok!下面就finish了。
2、注意事項
先看applicationContext.xml的配置
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath:/com/wemobil/entity/*.hbm.xml</value>
</list>
</property>
</bean>
<!-- 使用annotation自動註冊bean,並檢查@Required,@Autowired的屬性已被注入 -->
<context:component-scan base-package="com.wemobil.*" />
<!-- 開啓註解事務 只對當前配置文件有效 -->
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
<!-- 配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置事務傳播特性 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<!--hibernate4必須配置爲開啓事務 否則 getCurrentSession()獲取不到 -->
<tx:method name="get*" read-only="true" />
<tx:method name="load*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="search*" read-only="true" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 配置哪些類的哪些方法參與事務 -->
<aop:config expose-proxy="true">
<aop:advisor pointcut="execution(* com.wemobil..*.*(..))"
advice-ref="transactionAdvice" />
</aop:config>
</beans>
其中,需要注意的有
1)不要忘了指明驅動程序
2)hibernate4需要指明hibernate.current_session_context_class參數爲,不可爲thread(不明所以,但確實因爲這個弄的頭都大了),否則會出現no session for current 。。。
3)配置mappingLocations來指明hibernate的映射文件位置,只是因爲本人忘記了故加以提醒
待發現新的問題會繼續補充,歡迎大家多多指點,把大家遇到的問題彙總彙總,方便大家。