如果不结合spring呢??相关代码如下:1 DAO接口package test.hibernate;import org.hibernate.Session; /** * Data access interface for domain model * @author MyEclipse - Hibernate Tools */ public interface IBaseHibernateDAO { public Session getSession(); }2 DAO基类package test.hibernate;import org.hibernate.Session;/** * Data access object (DAO) for domain model * @author MyEclipse - Hibernate Tools */ public class BaseHibernateDAO implements IBaseHibernateDAO {
public Session getSession() { return HibernateSessionFactory.getSession();; }
}3 SessionFactorypackage test.hibernate;import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration;/** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/dagl/hibernate/hibernate.cfg.xml"; private static final ThreadLocal threadLocal = new ThreadLocal(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; private HibernateSessionFactory() { }
/** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; }}
现在如果实际使用:1 实际的DAO如下package test.hibernate;import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.criterion.Example;/** * Data access object (DAO) for domain model class AppTbMenuitems. * @see com.modules.menu.strutsMenu.impl.hibernate.AppTbMenuitems * @author MyEclipse - Hibernate Tools */ public class AppTbMenuitemsDAO extends BaseHibernateDAO { private static final Log log = LogFactory.getLog(AppTbMenuitemsDAO.class); //property constants public static final String PATH = "path"; public static final String NAME = "name"; public static final String PARENT_ID = "parentId"; public static final String TEXT = "text"; public static final String TYPE = "type"; public static final String LINK = "link"; public static final String WIDTH = "width"; public static final String HEIGHT = "height"; public static final String ONCLICK = "onclick"; public static final String ONMOUSEOVER = "onmouseover"; public static final String ONMOUSEOUT = "onmouseout"; public static final String IMAGE = "image"; public static final String ALTIMAGE = "altimage"; public static final String TRAINORDER = "trainorder"; public void save(AppTbMenuitems transientInstance) { log.debug("saving AppTbMenuitems instance"); try { getSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } }
public List findByExample(AppTbMenuitems instance) { log.debug("finding AppTbMenuitems instance by example"); try { List results = getSession() .createCriteria("com.modules.menu.strutsMenu.impl.hibernate.AppTbMenuitems") .add(Example.create(instance)) .list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } }
public List findByProperty(String propertyName, Object value) { log.debug("finding AppTbMenuitems instance with property: " + propertyName + ", value: " + value); try { String queryString = "from AppTbMenuitems as model where model." + propertyName + "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByPath(Object path) { return findByProperty(PATH, path); }
public List findByName(Object name) { return findByProperty(NAME, name); }
public List findByParentId(Object parentId) { return findByProperty(PARENT_ID, parentId); }
public List findByText(Object text) { return findByProperty(TEXT, text); }
public List findByType(Object type) { return findByProperty(TYPE, type); }
public List findByLink(Object link) { return findByProperty(LINK, link); }
public List findByWidth(Object width) { return findByProperty(WIDTH, width); }
public List findByHeight(Object height) { return findByProperty(HEIGHT, height); }
public List findByOnclick(Object onclick) { return findByProperty(ONCLICK, onclick); }
public List findByOnmouseover(Object onmouseover) { return findByProperty(ONMOUSEOVER, onmouseover); }
public List findByOnmouseout(Object onmouseout) { return findByProperty(ONMOUSEOUT, onmouseout); }
public List findByImage(Object image) { return findByProperty(IMAGE, image); }
public List findByAltimage(Object altimage) { return findByProperty(ALTIMAGE, altimage); }
public List findByTrainorder(Object trainorder) { return findByProperty(TRAINORDER, trainorder); }
事物由SPRING来管理
/**
* Data access interface for domain model
* @author MyEclipse - Hibernate Tools
*/
public interface IBaseHibernateDAO {
public Session getSession();
}2 DAO基类package test.hibernate;import org.hibernate.Session;/**
* Data access object (DAO) for domain model
* @author MyEclipse - Hibernate Tools
*/
public class BaseHibernateDAO implements IBaseHibernateDAO {
public Session getSession() {
return HibernateSessionFactory.getSession();;
}
}3 SessionFactorypackage test.hibernate;import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory { /**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/dagl/hibernate/hibernate.cfg.xml";
private static final ThreadLocal threadLocal = new ThreadLocal();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION; private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} /**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} /**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} /**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
} /**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
} /**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;/**
* Data access object (DAO) for domain model class AppTbMenuitems.
* @see com.modules.menu.strutsMenu.impl.hibernate.AppTbMenuitems
* @author MyEclipse - Hibernate Tools
*/
public class AppTbMenuitemsDAO extends BaseHibernateDAO { private static final Log log = LogFactory.getLog(AppTbMenuitemsDAO.class); //property constants
public static final String PATH = "path";
public static final String NAME = "name";
public static final String PARENT_ID = "parentId";
public static final String TEXT = "text";
public static final String TYPE = "type";
public static final String LINK = "link";
public static final String WIDTH = "width";
public static final String HEIGHT = "height";
public static final String ONCLICK = "onclick";
public static final String ONMOUSEOVER = "onmouseover";
public static final String ONMOUSEOUT = "onmouseout";
public static final String IMAGE = "image";
public static final String ALTIMAGE = "altimage";
public static final String TRAINORDER = "trainorder";
public void save(AppTbMenuitems transientInstance) {
log.debug("saving AppTbMenuitems instance");
try {
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(AppTbMenuitems persistentInstance) {
log.debug("deleting AppTbMenuitems instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public AppTbMenuitems findById( java.lang.String id) {
log.debug("getting AppTbMenuitems instance with id: " + id);
try {
AppTbMenuitems instance = (AppTbMenuitems) getSession()
.get("com.modules.menu.strutsMenu.impl.hibernate.AppTbMenuitems", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(AppTbMenuitems instance) {
log.debug("finding AppTbMenuitems instance by example");
try {
List results = getSession()
.createCriteria("com.modules.menu.strutsMenu.impl.hibernate.AppTbMenuitems")
.add(Example.create(instance))
.list();
log.debug("find by example successful, result size: " + results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding AppTbMenuitems instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from AppTbMenuitems as model where model."
+ propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
} public List findByPath(Object path) {
return findByProperty(PATH, path);
}
public List findByName(Object name) {
return findByProperty(NAME, name);
}
public List findByParentId(Object parentId) {
return findByProperty(PARENT_ID, parentId);
}
public List findByText(Object text) {
return findByProperty(TEXT, text);
}
public List findByType(Object type) {
return findByProperty(TYPE, type);
}
public List findByLink(Object link) {
return findByProperty(LINK, link);
}
public List findByWidth(Object width) {
return findByProperty(WIDTH, width);
}
public List findByHeight(Object height) {
return findByProperty(HEIGHT, height);
}
public List findByOnclick(Object onclick) {
return findByProperty(ONCLICK, onclick);
}
public List findByOnmouseover(Object onmouseover) {
return findByProperty(ONMOUSEOVER, onmouseover);
}
public List findByOnmouseout(Object onmouseout) {
return findByProperty(ONMOUSEOUT, onmouseout);
}
public List findByImage(Object image) {
return findByProperty(IMAGE, image);
}
public List findByAltimage(Object altimage) {
return findByProperty(ALTIMAGE, altimage);
}
public List findByTrainorder(Object trainorder) {
return findByProperty(TRAINORDER, trainorder);
}
public AppTbMenuitems merge(AppTbMenuitems detachedInstance) {
log.debug("merging AppTbMenuitems instance");
try {
AppTbMenuitems result = (AppTbMenuitems) getSession()
.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
} public void attachDirty(AppTbMenuitems instance) {
log.debug("attaching dirty AppTbMenuitems instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(AppTbMenuitems instance) {
log.debug("attaching clean AppTbMenuitems instance");
try {
getSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
}
public boolean delItem(String id) {
boolean result=false;
AppTbMenuitemsDAO dao=new AppTbMenuitemsDAO();
dao.getSession().beginTransaction();
AppTbMenuitems bean = dao.findById(id);
if(bean!=null){
try{
dao.delete(bean);
dao.getSession()
.createQuery("delete AppTbMenuitems where path like :p1")
.setString("p1", bean.getPath()+"/%").executeUpdate();
result=true;
}catch(Exception e){
Log4J.error("删除主键为"+id+"的项失败", e);
}
}else{
Log4J.error("主键为"+id+"的项不存在");
}
if(result){
dao.getSession().getTransaction().commit();
}else{
dao.getSession().getTransaction().rollback();
}
dao.getSession().close();
return result;
}
dao层不涉及事务问题。应由业务层负责,比如由spring来代理.