簡體   English   中英

如何使用Hibernate Context會話創建通用DAO類

[英]How to create a Generic DAO class using Hibernate Context sessions

我正在嘗試使用休眠上下文會話來實現通用DAO。 以下是我的鏡頭:|

import java.io.Serializable;

public interface GenericDao<T, ID extends Serializable> {

 /** Persist the newInstance object into database */
 ID create(T newInstance);

 /**
  * Retrieve an object that was previously persisted to the database using
  * the indicated id as primary key
  */
 T read(ID primaryKey);

 /** Save changes made to a persistent object. */
 void update(T transientObject);

 /** Remove an object from persistent storage in the database */
 void delete(T persistentObject);
}


import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@SuppressWarnings("unchecked")
public class GenericDaoImpl<T, ID extends Serializable> implements
  GenericDao<T, ID> {
 private SessionFactory sessionFactory;

 public void setSessionFactory(final SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 @Override
 public ID create(final T newInstance) {
  ID id = null;
  final Session session = sessionFactory.openSession();
  final Transaction tx = session.beginTransaction();
  try {
   id = (ID) session.save(newInstance);
   tx.commit();
   session.close();
  } catch (final Exception e) {
   if (tx != null) {
    tx.rollback();
   }
   e.printStackTrace();
  } finally {
   if (session.isOpen()) {
    session.close();
   }
  }
  return id;
 }

 @Override
 public T read(final ID primaryKey) {
  T id = null;
  final Session session = sessionFactory.openSession();
  final Transaction tx = session.beginTransaction();
  try {
   id = (T) session.get(T, primaryKey);
   tx.commit();
   session.close();
  } catch (final Exception e) {
   if (tx != null) {
    tx.rollback();
   }
   e.printStackTrace();
  } finally {
   if (session.isOpen()) {
    session.close();
   }
  }
  return id;
 }

 @Override
 public void update(final T transientObject) {
  final Session session = sessionFactory.openSession();
  final Transaction tx = session.beginTransaction();
  try {
   session.saveOrUpdate(transientObject);
   tx.commit();
   session.close();
  } catch (final Exception e) {
   if (tx != null) {
    tx.rollback();
   }
   e.printStackTrace();
  } finally {
   if (session.isOpen()) {
    session.close();
   }
  }
 }

 @Override
 public void delete(final T persistentObject) {
  final Session session = sessionFactory.openSession();
  final Transaction tx = session.beginTransaction();
  try {
   session.delete(persistentObject);
   tx.commit();
   session.close();
  } catch (final Exception e) {
   if (tx != null) {
    tx.rollback();
   }
   e.printStackTrace();
  } finally {
   if (session.isOpen()) {
    session.close();
   }
  }
 }
}

applicationContext:

<bean id="domainDao" class="com.foo.dao.DomainDao">
  <property name="sessionFactory">
   <ref bean="sessionFactory"></ref>
  </property>

 </bean>

 <bean id="domainDao2" class="com.foo.dao.GenericDaoImpl">
  <property name="sessionFactory">
   <ref bean="sessionFactory"></ref>
  </property>

 </bean>
 <tx:annotation-driven transaction-manager="txManager" />


 <bean id="txManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

我們的程序是一個新應用程序,我們正在嘗試使用Spring 3.0.3和Hibernate 3.5.5來實現。

Q1。 盡管我確實實現了它並且可以正常工作,但是我是否以正確的方式做到了?

Q2。 如何使用泛型實現find()操作?

id = (T) session.get(T, primaryKey);

該行顯示編譯錯誤。

更新 :錯誤是因為第一個參數是Class類型。

public Object get(Class clazz, Serializable id)
           throws HibernateException

Q3。 怎么把T轉換成T.class

通用DAO類中經常使用以下技巧來訪問實際子類的類型參數:

public abstract class GenericDAO<T, ID extends Serializable> {  
    private Class<T> persistentClass;  
    ...

    @SuppressWarnings("unchecked")
    public GenericDAO() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public T get(ID id) {
        return (T) session.get(persistentClass, id);
    }

    ...
}

和實際的DAO子類:

public class FooDAO extends GenericDAO<Foo, Long> {}

泛型不能以這種方式使用。 更改您的GenericDAOImpl以使其具有一個接受該類並在session.get調用中使用該類的session.get 請參見下面的示例(它使用JPA而不是Hibernate特定的類)。

public class GenericDao<T> {

    @PersistenceContext
    private EntityManager em;

    public EntityManager em() {
        return em;
    }

    public void create(final T entity) {
        em.persist(entity);
    }

    public void update(final T entity) {
        em.merge(entity);
    }

    protected T get(final Class<T> type, final String id) {
        return em.find(type, id);
    }

    public void delete(final T entity) {
        em.remove(entity);
    }

}

public class PersonDao extends GenericDao<Person>{

    public Person get(final String id) {
        return get(Person.class, id);
    }

}

另外,最好將@Transactional批注放在業務或數據服務上,而不要放在DAO上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM