本文共 2014 字,大约阅读时间需要 6 分钟。
Hibernate知识学习:
//首先在web.xml中加入OpenSessionInViewFilter过滤器
openSessionInViewFilter org.springframework.orm.hibernate4.support.OpenSessionInViewFilter openSessionInViewFilter /*
在applicationContext.xml中的sessionFactory 中 添加thread 属性
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=false hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=false hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider hibernate.current_session_context_class=thread
hibernate.cfg.xml test.cfg.xml
在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; } @Override public void saveMessage(TestMessage tm) { Session session = this.getSession(); Transaction tran = session.beginTransaction(); session.save(tm); tran.commit(); } @Override public String getMessage() { Session session = this.getSession(); Transaction tran = session.beginTransaction(); Listdatas = session.createQuery("From TestMessage").list(); tran.commit(); return datas.get(7).getContent(); }}
转载地址:http://nrxea.baihongyu.com/