假设载入 Hibernate3 框架。
其中 HibernateSessionFactory.java 置于 org.stephencat.hibernate 中。
实体DAOFactory 引用资源如下:
Session session; (Session 来自 org.hibernate.Session )
Transaction tx; (Transaction 来自 org.hibernate.Transaction)
DAOFactory方法示例:
public void add(Admin admin) throws HibernateException {
try {
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
// Add a new admin
session.save(admin);
tx.commit();
} catch (HibernateException e) {
throw e;
} finally {
if (tx != null) {
tx.rollback();
}
HibernateSessionFactory.closeSession();
}
}
try {
session = HibernateSessionFactory.currentSession();
tx = session.beginTransaction();
// Add a new admin
session.save(admin);
tx.commit();
} catch (HibernateException e) {
throw e;
} finally {
if (tx != null) {
tx.rollback();
}
HibernateSessionFactory.closeSession();
}
}
Action 方法示例如下:
// TODO Auto-generated method stub
Admin admin = new Admin();
admin.setName(addAdminForm.getName());
admin.setPassword(addAdminForm.getPassword());
AdminDAOFactory adminDAO = new AdminDAOFactory();
adminDAO.add(admin);
return mapping.findForward("success");
Admin admin = new Admin();
admin.setName(addAdminForm.getName());
admin.setPassword(addAdminForm.getPassword());
AdminDAOFactory adminDAO = new AdminDAOFactory();
adminDAO.add(admin);
return mapping.findForward("success");
Form 引用资源如下:
ActionErrors errors = ......; (ActionErrors 和 ActionMessage 来自 org.apache.struts.action.*)
Session session = ......; (Session 来自 org.hibernate.Session )
Transaction tx = ......; (Transaction 来自 org.hibernate.Transaction )
Query query = ......; (Query 来自 org.hibernate.Query )
Iterator it = ......; (Iterator 来自 java.util.Iterator )
Form validate 方法示例:
ActionErrors errors = new ActionErrors();
Session session = HibernateSessionFactory.currentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("select admin from Admin as admin where admin.name='"+this.name+"'");
Iterator it = query.iterate();
if(it.hasNext()){
errors.add("addAdmin.err.name",new ActionMessage("form.addAdmin.err.name"));
}
tx.commit();
HibernateSessionFactory.closeSession();
return errors;
Session session = HibernateSessionFactory.currentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("select admin from Admin as admin where admin.name='"+this.name+"'");
Iterator it = query.iterate();
if(it.hasNext()){
errors.add("addAdmin.err.name",new ActionMessage("form.addAdmin.err.name"));
}
tx.commit();
HibernateSessionFactory.closeSession();
return errors;