-
Notifications
You must be signed in to change notification settings - Fork 212
Hibernate and Generic DAOs
Microserver makes configuring hibernate simple.
@Microserver(springClasses = { Classes.HIBERNATE_CLASSES}, entityScan = "com.my.hibernate.entities")
Microserver will include a Generic Hibernate DAO as a Spring bean, once Hibernate has been switched on via the Microserver (or Microboot) annotation. It provides a range of powerful Generic DAO methods for any entity out of the box, and it is a handy way to quickly build a mini-domain model for a Microservice. For full details on available methods check out the Generic Hibernate DAO website.
By using the DAOProvider bean provided by Microserver, we can create a GenericHibernateService class for any entity.
E.g. 👍
private final GenericHibernateService<HibernateEntity,Long> service;
@Autowired
public PersistentResource(DAOProvider<HibernateEntity,Long> daoProvider) {
service = daoProvider.get(HibernateEntity.class);
}
We can now query for our entities as follows
service.save(entity);
or to do a complex find
service.<HibernateEntity>search(new Search()
.addFilter(dao.getFilterFromExample(exampleEntity));
To turn on Hibernate with JPA repositories also include the @EnableJpaRepositories annotation on your main class or a configuration class in the directory containing your repos - and add the SPRING_DATA_CLASSES to Microserver. E.g.
@Microserver(springClasses = { Classes.HIBERNATE_CLASSES, Classes.SPRING_DATA_CLASSES}, entityScan = "com.my.hibernate.entities")
@EnableJpaRepositories
public class HibernateRunnerTest
The create a repository interface that extends CrudRespository
public interface HibernateEntityRepository extends CrudRepository<HibernateEntity, Long> {
}
You will then have CRUD repo for your DAO and can add new methods via interface method definitions in the standard Spring Data manner. For more details checkout the Spring Data docs