My web application has got a lot of service tables/entities, such as payment_methods
, tax_codes
, province_codes
, etc.
Each time I add a new entity, I have to write a DAO. The thing is that, basically, they are all the same, but the only difference is the entity class itself.
I know that Hibernate tools can generate the code for me automatically but I can't use them now (don't ask why) so I'm thinking of a Generic DAO. There's a lot of literature about that but I can't put pieces together and make it work with Spring.
It's all about generics I think, it will have four basic methods:
listAll
saveOrUpdate
deleteById
getById
and that's all.
What's the best practice for not re-inventing the wheel? Isn't there something ready to use, yet?
GenericDAO is a class that can be extended to make individual DAOs. A basic domain-object-specific DAO is created by extending GenericDAO and specifying the domain object type with generic type parameters. The default implementation can be customized by adding and/or overriding methods.
GenericDAO is a method to reduce boilerplate sources codes. EmployeesResource class. CRUD operations on WEB API.
This is an example of how to create Data Access Objects (DAOs), making use of the Hibernate implementation for the Java Persistence API (JPA) specification.
One of the core objectives of Spring Data JPA is to reduce your code and simplify your Data Access Layer, while still maintaining a rich and full-featured set of functionality. To make this possible, Spring DATA JPA allows you to build intelligent Spring Repository stereotyped interfaces.
here's mine
@Component public class Dao{ @Resource(name = "sessionFactory") private SessionFactory sessionFactory; public <T> T save(final T o){ return (T) sessionFactory.getCurrentSession().save(o); } public void delete(final Object object){ sessionFactory.getCurrentSession().delete(object); } /***/ public <T> T get(final Class<T> type, final Long id){ return (T) sessionFactory.getCurrentSession().get(type, id); } /***/ public <T> T merge(final T o) { return (T) sessionFactory.getCurrentSession().merge(o); } /***/ public <T> void saveOrUpdate(final T o){ sessionFactory.getCurrentSession().saveOrUpdate(o); } public <T> List<T> getAll(final Class<T> type) { final Session session = sessionFactory.getCurrentSession(); final Criteria crit = session.createCriteria(type); return crit.list(); } // and so on, you shoudl get the idea
and you can then access like so in service layer:
@Autowired private Dao dao; @Transactional(readOnly = true) public List<MyEntity> getAll() { return dao.getAll(MyEntity.class); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With