自己写了个工具类如下:public void closeSession(Session session) {
// TODO Auto-generated method stub
if(session!=null){
session.close();
}
} public void rollBackTransaction(Transaction tr) {
// TODO Auto-generated method stub
if(tr!=null){
tr.rollback();
}
} public Session getSession() {
// TODO Auto-generated method stub
return getSessionFactory().openSession();
} public SessionFactory getSessionFactory() {
Configuration cfg = new Configuration().configure();
return cfg.buildSessionFactory();
} public Transaction getTransaction() {
// TODO Auto-generated method stub
return getSession().beginTransaction();
}上面是封装的方法下面是测试的
public static void main(String args[]){
HibernateClient o = new HibernateClient();
Product po = new Product();
po.setName("testname");
po.setDescription("ORM Frame");
o.saveProduct(po);
}
public void saveProduct(Product p){
Session session = null;
Transaction tr = null;
try{
session = getSession();
tr = getTransaction();
session.save(p);
tr.commit();
}catch(HibernateException e){
e.printStackTrace();
}finally{
session.close();
}
很奇怪,就是存不进去,但是如果我用HibernateSessionFactory.getSession()就可以存数据。
我的getSession()方法中也是正确的啊先谢了
// TODO Auto-generated method stub
if(session!=null){
session.close();
}
} public void rollBackTransaction(Transaction tr) {
// TODO Auto-generated method stub
if(tr!=null){
tr.rollback();
}
} public Session getSession() {
// TODO Auto-generated method stub
return getSessionFactory().openSession();
} public SessionFactory getSessionFactory() {
Configuration cfg = new Configuration().configure();
return cfg.buildSessionFactory();
} public Transaction getTransaction() {
// TODO Auto-generated method stub
return getSession().beginTransaction();
}上面是封装的方法下面是测试的
public static void main(String args[]){
HibernateClient o = new HibernateClient();
Product po = new Product();
po.setName("testname");
po.setDescription("ORM Frame");
o.saveProduct(po);
}
public void saveProduct(Product p){
Session session = null;
Transaction tr = null;
try{
session = getSession();
tr = getTransaction();
session.save(p);
tr.commit();
}catch(HibernateException e){
e.printStackTrace();
}finally{
session.close();
}
很奇怪,就是存不进去,但是如果我用HibernateSessionFactory.getSession()就可以存数据。
我的getSession()方法中也是正确的啊先谢了
解决方案 »
- 初学struts2,遇到一个关于namespace的问题,查阅过很多资料一直没找到答案,请求高手指教!
- 用jspSmartUpload下载超长文件名不能完全显示?
- j2ee 依然内存问题
- 怎样在浏览器首次加载图片时获得正确的图片长宽?
- forward问题
- 征集jsp/servlet乱码解决方案,最好能够有个终极解决办法
- 什么语句可以自己执行.就像response.sendRedirect();
- 请帮看一下这个jsp那儿出错,在线等待.
- 怎么样把JSP页面生成HTML静态页面呀?
- 我的jdk装好后,能用java,但是不能用javac,大家帮忙看看?
- 谁能推荐个基于SIMPLE协议的IM
- 工作5年也答不上来的面试题
tr = getTransaction();这两个session是一个session吗?tr是另一个session的,事务没有提交
session = getSession();
tr = getTransaction();