关于MyEclipse中使用Hibernate生成DAO的问题,大家帮忙,急

suncjt1 2007-07-11 11:37:37
使用MyEclipse组建Hibernate时,会自动创建,HibernateSessionFactory 和 IBaseHibernateDAO 接口, 其他的DAO会实现此接口的扩展。

我的问题是,这么设计的好处是什么???如果使用事务时应该如何操作。如果每次都调用 dao的getSession方法的话,如何确保从SessionFactory中调用的是同一个Session啊?????
...全文
2932 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
z249683156 2010-08-06
  • 打赏
  • 举报
回复
关注中!!我也想这样,但是在java的工程中实现了,在web的工程中失败了!!我都不知道什么原因
suncjt1 2007-07-11
  • 打赏
  • 举报
回复
此处的 dao层确实也没有涉及到事务啊 ,外面的业务层应该怎么写???在不使用spring的前提下!!
suncheng_hong 2007-07-11
  • 打赏
  • 举报
回复
一般不会用它自已生成的框架,框架是根据需要来的.
dao层不涉及事务问题。应由业务层负责,比如由spring来代理.
suncjt1 2007-07-11
  • 打赏
  • 举报
回复
问题:

1我使用此上面的dao进行相关业务操作应该如何写(使用事务)??

代码如下:对么???(大家帮忙,分不够可以加)


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;
}
suncjt1 2007-07-11
  • 打赏
  • 举报
回复
现在如果实际使用:

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 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;
}
}
}
suncjt1 2007-07-11
  • 打赏
  • 举报
回复
如果不结合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 SessionFactory

package 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;
}

}
Ryo_Hazuki 2007-07-11
  • 打赏
  • 举报
回复
建议和SPRING结合使用
事物由SPRING来管理
qsz888 2007-07-11
  • 打赏
  • 举报
回复
我们现在用的是struts+spring+hibernate,没考虑过struts+hibernate的情况,关注。。。。。。。。。。

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧