看到很多资料在使用spring框架后,为每个表对应的POJO写一个DAO接口,再写一个实现类,每个接口里都是简单的CRUD操作,感觉实在很麻烦
以前的项目里直接用struts+hibernate,有一个DbOperate类,来历不知,但它的CRUD方法可以对所有类操作,这样不是更简单?各位瞧瞧
public class DbOperate {
public boolean save(Object obj) throws HibernateException {
boolean result = false;
Session session = SessionFactory.currentSession();
if (obj != null) {
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(obj);
tx.commit();
result = true;
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
result = false;
}
} finally {
session.close();
return result;
}
}
return result;
}
public void update(Object obj) throws HibernateException {
Session session = SessionFactory.currentSession();
if (obj != null) {
Transaction tx = null;
try {
tx = session.beginTransaction();
////System.out.println("aaaa");
session.update(obj);
////System.out.println("bbbb");
tx.commit();
////System.out.println("cccc");
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e;
}
}
session.close();
}
public void delete(Object obj) throws HibernateException {
Session session = SessionFactory.currentSession();
if (obj != null) {
Transaction tx = null;
try {
tx = session.beginTransaction();
session.delete(obj);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e;
}
}
session.close();
}
public void saveOrUpdate(Object obj) throws HibernateException {
Session session = SessionFactory.currentSession();
if (obj != null) {
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(obj);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e;
}
}
session.close();
}
public List find(String sql) throws HibernateException {
Session session = SessionFactory.currentSession();
List list = null;
Transaction tx = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery(sql);
list = query.list();
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e;
}
session.close();
return list;
}
}