📄 abstractdao.java
字号:
package com.manning.hq.ch08;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import java.util.List;
/**
* A layer supertype that handles the common operations for all Data Access Objects.
*/
public abstract class AbstractDao {
private Session session;
private Transaction tx;
public AbstractDao() {
HibernateFactory.buildIfNeeded();
}
protected Session getSession() {
return session;
}
protected Transaction getTx() {
return tx;
}
protected void saveOrUpdate(Object obj) {
try {
startOperation();
session.saveOrUpdate(obj);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateFactory.close(session);
}
}
protected void delete(Object obj) {
try {
startOperation();
session.delete(obj);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateFactory.close(session);
}
}
protected Object find(Class clazz, Long id) {
Object obj = null;
try {
startOperation();
obj = session.load(clazz, id);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateFactory.close(session);
}
return obj;
}
protected List findAll(Class clazz) {
List objects = null;
try {
startOperation();
objects = session.find("from " + clazz.getName());
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateFactory.close(session);
}
return objects;
}
protected void handleException(HibernateException e) throws DataAcessLayerException {
HibernateFactory.rollback(tx);
throw new DataAcessLayerException(e);
}
protected void startOperation() throws HibernateException {
session = HibernateFactory.openSession();
tx = session.beginTransaction();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -