Reputation: 165
I am using generics to build a DAO. The database could be any database. The problem is that for each type of class there is a specific class. For example:
public class DAO<T> {
public void save(T entity) {
}
}
public class StudentDAO extends DAO<Student> {
}
Just imagine I have 1000 tables or more. Do I need to have 1000 classes like this? Is there a better way to design this?
Edit
I am using MongoDB a NoSQL database with Spring MongoDB. It has Repository concept through Spring but I will still end up with 1000 classes. I cannot use JPA or Hibernate. Any other solution?
Upvotes: 1
Views: 1912
Reputation: 14309
Yes there is definitely a better way. What you bumped into is what I call the "DAO-per-entity scalability issue". What you need for that is a reusable Generic DAO implementation e.g. PerfectJPattern
IGenericDao<Long, Customer> myCustomerDao = HibernateDaoFactory.getInstance().createDao(Customer.class);
// create a Customer
Customer myCustomer1 = new Customer(/*name=*/"Pedro");
myCustomerDao.create(myCustomer1);
// find all customers whose name is "Juan"
List<Customer> myMatches = myCustomerDao.findByExample(new Customer(/*name=*/"Juan"));
what just happened here? you don't need to create a new CustomerDao
but reuse the generic one. In addition to the basic CRUD, you may even cover 90% of your "finder" needs using the findByExample
see IGenericReadOnlyDao.
If the findByExample
does not cover all your needs then you have the choice to use the Spring level Generic DAO, example here that offers direct mapping from SQL to your DAO interface and you don't need to provide an implementation.
Upvotes: 1
Reputation: 354
You don't have to extend DAO class. I assume DAO constructor has a parameter to detect which entity and which table it should interact with. Something like this:
public DAO(Class<T> type) {
this.persistentType = type;
}
With such constructor, wherever you need a DAO instance for Student entity you can initialize it like this:
DAO<Student> studentDao = new DAO<Student>(Student.class);
Upvotes: 1
Reputation: 115328
You can do it. But I'd recommend you to use Generic Dao project. It supports both native Hibernate and JPA API and allows you to create one and only one DAO for all entities you have.
Upvotes: 1
Reputation: 10997
Consider Spring Data , which will generate DAO layer for you.
Upvotes: 0