Wednesday, 4 July 2018

GenericDaoImpl


@Repository

@Transactional(readOnly = true)

@SuppressWarnings({ "unchecked", "serial" })

public abstract class GenericDaoImpl<E, ID extends Serializable> extends

HibernateTemplate implements GenericDao<E, ID> {

protected Class<E> entityClass;
public GenericDaoImpl() {

setEntityClass(); 

}

public E findById(ID id, boolean lock) {

return (E) super.get(entityClass, id);

}

public E findById(ID id) {

return findById(id, false);

}

public List<E> findAll() throws Exception {

return this.loadAll(entityClass);

}

public List<E> findByCriteria(DetachedCriteria criteria, int startIndex,

int maxResults) {

return (List<E>) super.findByCriteria(criteria, startIndex, maxResults);

}

@Autowired

@Qualifier("hibernateSessionFactory")

public void setSessionFactory(SessionFactory hibernateSessionFactory) {

super.setSessionFactory(hibernateSessionFactory);



}

protected void setEntityClass() {

entityClass = (Class<E>) ((ParameterizedType) getClass()

.getGenericSuperclass()).getActualTypeArguments()[0];

}



@Transactional(readOnly = false, propagation = Propagation.REQUIRED)

public E makePersistent(E entity) {

this.checkWriteOperationAllowed(getSession());

this.saveOrUpdate(entity);

return entity;

}



@Transactional(readOnly = false, propagation = Propagation.REQUIRED)

public void deleteEntity(E entity) {

this.checkWriteOperationAllowed(getSession());

this.delete(entity);

}



@Transactional(readOnly = false, propagation = Propagation.REQUIRED)

public void deleteAllEntities(Collection<E> entities) {



for (E entity : entities) {

this.checkWriteOperationAllowed(getSession());

this.delete(entity);

}

}

@Override

public Session getSession() {
Session session = getSessionFactory().getCurrentSession();

session.setFlushMode(FlushMode.COMMIT);

return session;

}

}

No comments:

Post a Comment