Write Less DAOs with Spring Hibernate using Annotations

我的梦境 提交于 2019-12-04 08:33:45

Using generics, you might try something like this:

@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);
    }

}

The content may be different, but the general idea is applicable.

You should be able to then autowire the DAO in your controller and service classes by using

@Autowired
private GenericDAO<Car> carDao;

You can combine Spring/Hibernate with JPA, which provides the EntityManager for a large amount of basic persistence tasks:

@Service
public class CarService {

    @PersistenceContext
    private EntityManager em;

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

It will also handle transactions and simple queries without needing to write a DAO. For the more complex operations, you can still write a DAO and fall back to Hibernate's SessionFactory (although JPA is an option here too).

Some tutorials suggest you should still write the DAO for abstraction of the JPA plumbing. However, I have personally found this unnecessary (JPA has a very small integration footprint), and in fact this is also the way Spring Roo deals with the data layer behind the scenes.

Have you tried to use Spring Data. I mean to say Spring JPA where you can use repositories.
You can eliminate writing all stuffs for each entity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!