1.我用的 Myeclipse自动生成的代码,session是在Threadlocal中管理的.那么比如在DAO类中我是不是每个方法最后都应该调用getSession().close();?还是永远把这个session留在Threadlocal中?2.DAO类中从设计角度来说封装到什么程度比较好?Myeclipse自动生成的代码这样行吗?还是说需要把
Transaction tx= etrdao.getSession().beginTransaction();
....
tx.commit();
这样的代码重新封在DAO类中,建立比如addUser(User user)之类的方法?3.hibernate中的autocommit()到底怎么设为true?我在hibernate.cfg.xml中增加了<property name="hibernate.connection.autocommit">true</property>
但是我的代码
ExceptiontyperefDAO etrdao=new ExceptiontyperefDAO();
etrdao.getSession().connection().setAutoCommit(true);
Exceptiontyperef er=new Exceptiontyperef();
er.setTypeid(14L);
er.setPriority(5L);
er.setDescription("为了hibernate");
etrdao.save(er);
etrdao.getSession().close();
还在数据库中还是看不到数据
而加上Transaction tx= etrdao.getSession().beginTransaction();tx.commit();之后数据库中就可以看到更新后的数据了.我不愿意在每个方法里都加上事务操作,那么怎么像jdbc那样setautocommit(true)?
Transaction tx= etrdao.getSession().beginTransaction();
....
tx.commit();
这样的代码重新封在DAO类中,建立比如addUser(User user)之类的方法?3.hibernate中的autocommit()到底怎么设为true?我在hibernate.cfg.xml中增加了<property name="hibernate.connection.autocommit">true</property>
但是我的代码
ExceptiontyperefDAO etrdao=new ExceptiontyperefDAO();
etrdao.getSession().connection().setAutoCommit(true);
Exceptiontyperef er=new Exceptiontyperef();
er.setTypeid(14L);
er.setPriority(5L);
er.setDescription("为了hibernate");
etrdao.save(er);
etrdao.getSession().close();
还在数据库中还是看不到数据
而加上Transaction tx= etrdao.getSession().beginTransaction();tx.commit();之后数据库中就可以看到更新后的数据了.我不愿意在每个方法里都加上事务操作,那么怎么像jdbc那样setautocommit(true)?
2, 在DAO加入事务管理并不是一种好的做法,这种做法没有办法将一些相关的操作放在一个事务中去。当然,简单的开发不会出现问题
3, 可以使用Session.setFlushMode(FlushMode.AUTO);