Hibernate的SessionFactory在每个DAO中还是仅在扩展类中?

发布于 2024-11-07 04:02:00 字数 1241 浏览 2 评论 0原文

我在 HibernateDaoSupport 上使用 getSession() 遇到了一些大问题,现在当我尝试修复它时,我想知道创建如下所示的抽象类是否正确并使所有 Dao 都扩展它,而不是在每个 Dao 中添加 SessionFactory ?

如果是的话,那么一旦其他 Dao 扩展了它,创建这个抽象 Dao 类的 bean 并将其传递给会话工厂是否可以工作?或者说这根本不可能?

public abstract class AbstractDAOImpl<T> implements
        AbstractDAO<T> {

    private static Logger   _logger = LoggerFactory
                                    .getLogger(AbstractDAOImpl.class);
    private SessionFactory  factory;

    @Override
    public void refresh(final T object) {
        try {
            factory.getCurrentSession().refresh(object);
        } catch (Exception e) {
            _logger.error("Cannot refresh object " + object, e);
        }
    }

    @Override
    public void remove(final T object) {
        try {
            factory.getCurrentSession().delete(object);
        } catch (Exception e) {
            _logger.error("Cannot remove object " + object, e);
        }
    }

    @Override
    public void save(final T object) {
        try {
            factory.getCurrentSession().saveOrUpdate(object);
        } catch (Exception e) {
            _logger.error("Cannot save or update object " + object, e);
        }
    }

}

I run in few huge problems by using getSession() on HibernateDaoSupport and now when i try to fix it I was wondering if it is right to make a abstract class like this bellow and make all Dao's to extend it instead of adding SessionFactory in each Dao ?

If it is, then would creating bean of this abstract Dao class and passing it the session factory then work once other Dao's extend it? Or that is not even possible?

public abstract class AbstractDAOImpl<T> implements
        AbstractDAO<T> {

    private static Logger   _logger = LoggerFactory
                                    .getLogger(AbstractDAOImpl.class);
    private SessionFactory  factory;

    @Override
    public void refresh(final T object) {
        try {
            factory.getCurrentSession().refresh(object);
        } catch (Exception e) {
            _logger.error("Cannot refresh object " + object, e);
        }
    }

    @Override
    public void remove(final T object) {
        try {
            factory.getCurrentSession().delete(object);
        } catch (Exception e) {
            _logger.error("Cannot remove object " + object, e);
        }
    }

    @Override
    public void save(final T object) {
        try {
            factory.getCurrentSession().saveOrUpdate(object);
        } catch (Exception e) {
            _logger.error("Cannot save or update object " + object, e);
        }
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烈酒灼喉 2024-11-14 04:02:00
public interface RootDAO<T> extends Serializable {

    public List<T> loadAll();

    public T save(T entity);

    public void delete(T entity);

    public void markAsDeleted(T entity);

    public T get(Serializable id);

    public T load(Serializable id);

    public void saveOrUpdate(T entity);

    public void deleteAll(Collection<T> entities);

    public void saveOrUpdateAll(Collection<T> entities);

    public List<T> find(String hql);

    public void update(T entity);

    public T getByExampleUnique(T entity);

    public List<T> getByExampleList(T entity);

    public List<T> listAll();

    public Object execute(HibernateCallback action);

    public List<T> findByNamedParam(String queryString, String paramName,Object value);

    public List<T> findByNamedParam(String queryString, String[] paramNames,Object[] values);
    .
    .
    .
    .

}

@Component
public abstract class RootDAOImpl<T> extends HibernateDaoSupport implements RootDAO<T> {


    protected Logger logger = LoggerFactory.getLogger(getClass());
    private Class<T> clazz;

    @Autowired
    public void init(SessionFactory factory) {
        setSessionFactory(factory);
    }

    public RootDAOImpl(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void delete(T entity) {
        getHibernateTemplate().delete(entity);
    }

    public void delete(String id) {
        getHibernateTemplate().delete(new FbUser(id));
    }

    public void markAsDeleted(T entity) {
        // Mark entity as deleted
        try {
            Method setDeletedMethod = clazz.getDeclaredMethod("setDeleted", Boolean.class);
            setDeletedMethod.invoke(entity, true);
            getHibernateTemplate().saveOrUpdate(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // actually delete
        // getHibernateTemplate().delete(entity);
    }

    @Override
    public void deleteAll(Collection<T> entities) {
        getHibernateTemplate().deleteAll(entities);
    }

    @Override
    public void saveOrUpdateAll(Collection<T> entities) {
        getHibernateTemplate().saveOrUpdateAll(entities);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T get(Serializable id) {
        return (T) getHibernateTemplate().get(clazz, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T load(Serializable id) {
        return (T) getHibernateTemplate().load(clazz, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> find(String hql) {
        return (List<T>) getHibernateTemplate().find(hql);
    }

    @Override
    public Object execute(HibernateCallback action) {
        return getHibernateTemplate().execute(action);
    }


    .
    .
    .

}

@Repository
public class UserDAOImpl extends RootDAOImpl<User> implements UserDAO{


    public UserDAOImpl() {
        super(User.class);
    }
}

如果您不使用 DI 框架,您可能需要保留 SessionFactory 的引用,并在创建 DAO 实例时自行传递它。

public interface RootDAO<T> extends Serializable {

    public List<T> loadAll();

    public T save(T entity);

    public void delete(T entity);

    public void markAsDeleted(T entity);

    public T get(Serializable id);

    public T load(Serializable id);

    public void saveOrUpdate(T entity);

    public void deleteAll(Collection<T> entities);

    public void saveOrUpdateAll(Collection<T> entities);

    public List<T> find(String hql);

    public void update(T entity);

    public T getByExampleUnique(T entity);

    public List<T> getByExampleList(T entity);

    public List<T> listAll();

    public Object execute(HibernateCallback action);

    public List<T> findByNamedParam(String queryString, String paramName,Object value);

    public List<T> findByNamedParam(String queryString, String[] paramNames,Object[] values);
    .
    .
    .
    .

}

@Component
public abstract class RootDAOImpl<T> extends HibernateDaoSupport implements RootDAO<T> {


    protected Logger logger = LoggerFactory.getLogger(getClass());
    private Class<T> clazz;

    @Autowired
    public void init(SessionFactory factory) {
        setSessionFactory(factory);
    }

    public RootDAOImpl(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void delete(T entity) {
        getHibernateTemplate().delete(entity);
    }

    public void delete(String id) {
        getHibernateTemplate().delete(new FbUser(id));
    }

    public void markAsDeleted(T entity) {
        // Mark entity as deleted
        try {
            Method setDeletedMethod = clazz.getDeclaredMethod("setDeleted", Boolean.class);
            setDeletedMethod.invoke(entity, true);
            getHibernateTemplate().saveOrUpdate(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // actually delete
        // getHibernateTemplate().delete(entity);
    }

    @Override
    public void deleteAll(Collection<T> entities) {
        getHibernateTemplate().deleteAll(entities);
    }

    @Override
    public void saveOrUpdateAll(Collection<T> entities) {
        getHibernateTemplate().saveOrUpdateAll(entities);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T get(Serializable id) {
        return (T) getHibernateTemplate().get(clazz, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T load(Serializable id) {
        return (T) getHibernateTemplate().load(clazz, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> find(String hql) {
        return (List<T>) getHibernateTemplate().find(hql);
    }

    @Override
    public Object execute(HibernateCallback action) {
        return getHibernateTemplate().execute(action);
    }


    .
    .
    .

}

@Repository
public class UserDAOImpl extends RootDAOImpl<User> implements UserDAO{


    public UserDAOImpl() {
        super(User.class);
    }
}

If you are not using a DI framework you may need to keep a reference for SessionFactory and pass it yourself when you create the DAO instance.

记忆之渊 2024-11-14 04:02:00

这正是人们使用 hibernate 实现 JPA 的原因。您只需要开始使用 JPA 的 EntityManager,它以最佳的设计模式利用 SessionFactory 本身。您不必在这里重新发明整个设计模式。您所需要做的只是在每个 DAO 中使用 EntityManager 的 CRUD 操作,如以下示例所示。祝您实施一切顺利。

http://www .myhomepageindia.com/index.php/2009/04/02/jpa-hibernate-with-oracle-on-eclipse.html

This is exactly why people use JPA implementation by hibernate. You just need to start using the JPA's EntityManager which leverages on SessionFactory by itself in the best possible design patterns. You dont have to reinvent the whole design patterns here. All you need to do is just use CRUD operations of EntityManager in each of your DAO as shown in the following example. All the best with your implementation.

http://www.myhomepageindia.com/index.php/2009/04/02/jpa-hibernate-with-oracle-on-eclipse.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文