當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring3 整合 Hibernate4实现数据库操作(1)
生活随笔
收集整理的這篇文章主要介紹了
Spring3 整合 Hibernate4实现数据库操作(1)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Hibernate知識學習:http://justsee.iteye.com/blog/1061576
注意Hibernate4在開發當中的一些改變? :http://snake-hand.iteye.com/blog/1995592
//首先在web.xml中加入OpenSessionInViewFilter過濾器<filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter><filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 在applicationContext.xml中的sessionFactory 中 添加<property name="hibernate.current_session_context_class">thread</property> 屬性 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><!-- 依賴注入數據源,正式上下文定義的dataSource --><property name="dataSource" ref="dataSource" /><property name="hibernateProperties"><value>hibernate.dialect=org.hibernate.dialect.MySQL5Dialecthibernate.hbm2ddl.auto=updatehibernate.show_sql=truehibernate.format_sql=falsehibernate.cache.use_second_level_cache=truehibernate.cache.use_query_cache=falsehibernate.cache.provider_class=org.hibernate.cache.EhCacheProviderhibernate.current_session_context_class=thread</value></property><!--通過配置文件的方式獲取數據源--><property name="mappingResources"><list><!-- 以下用來列出所有的PO映射文件 --><value>hibernate.cfg.xml</value><value>test.cfg.xml</value></list></property> </bean> 在dao層部分的代碼如下,通過sessionFactory可以獲得當前的事務的session,通過session實現對數據庫的操作
public class MessageDaoImpl implements MessageDao{private SessionFactory sessionFactory; public Session getSession() { return sessionFactory.getCurrentSession(); } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Overridepublic void saveMessage(TestMessage tm) {Session session = this.getSession();Transaction tran = session.beginTransaction();session.save(tm); tran.commit();}@Overridepublic String getMessage() {Session session = this.getSession();Transaction tran = session.beginTransaction();List<TestMessage> datas = session.createQuery("From TestMessage").list();tran.commit();return datas.get(7).getContent();} }
轉載于:https://www.cnblogs.com/hujunzheng/p/4365578.html
總結
以上是生活随笔為你收集整理的Spring3 整合 Hibernate4实现数据库操作(1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 澳洲布洛亚克酒多少钱一瓶?
- 下一篇: 金条plus借款可以用吗