Burn less DAO with Spring Hibernate using annotations

My Spring + Hibernate configuration files are small and very tough. I use auto scan to find my / daos models.

I do not want to write DAO + DAOImpl for EVERY entity in my hierarchy.

Some may claim their own, for example, if they have complex relationships with other objects and require more than the basic CRUD functions. But for the rest ...

Is there a way around the defacto standard?

Say something like a generic DAO, for example:

http://www.ibm.com/developerworks/java/library/j-genericdao/index.html

Then I can do something like

  GenericDao dao = appContext.getBean("genericDao");
  dao.save(car);            
  dao.save(lease);

Is this possible with annotations? I do not want to configure anything in xml. If I cannot do the above, is it possible yet another GenericDaoImpl.java with something like:

 @Repository("carDao")
 @Repository("leaseDao")
 class GenericDaoImpl extends CustomHibernateDaoSupport implements GenericDao {
 ...
 }

and then

  GenericDao dao = appContext.getBean("carDao");
  dao.save(car);            
  dao = appContext.getBean("leaseDao"); //carDao is garbage coll.
  dao.save(lease);

Is this generally practical?

+5
3

generics, - :

@Repository
@Transactional
public class GenericDAOImpl<T> implements GenericDAO<T> {

    @Autowired
    private SessionFactory factory;

    public void persist(T entity) {
        Session session = factory.getCurrentSession();
        session.persist(entity);
    }

    @SuppressWarnings("unchecked")
    public T merge(T entity) {
        Session session = factory.getCurrentSession();
        return (T) session.merge(entity);
    }

    public void saveOrUpdate(T entity) {
        Session session = factory.getCurrentSession();
        session.saveOrUpdate(entity);
    }

    public void delete(T entity) {
        Session session = factory.getCurrentSession();
        session.delete(entity);
    }

}

, .

DAO

@Autowired
private GenericDAO<Car> carDao;
+5

Spring/Hibernate JPA, EntityManager :

@Service
public class CarService {

    @PersistenceContext
    private EntityManager em;

    public void saveCarAndLease(Car car, Lease lease) {
        em.persist(car);
        em.persist(lease);
    }
}

DAO. DAO Hibernate SessionFactory ( JPA ).

DAO JPA. , (JPA ), Spring Roo .

+2

Spring . Spring JPA, .
.

+1

All Articles