I created a common method in which I will pass a DAO but it will not be a one DAO. Like i will be passing not only StudentDao but also TeachersDao and ClubsDao.
Originally, this is my method:
public static String getSomething(StudentDao, String id){
Properties proFind = new Properties();
proFind.put(StudentDao.ID, id);
dao.select(proFind).get(0);
return somethingINeed;
}
But then I've decided that to use only one method, make it something generic.. Somthing like this:
public static <T> String getSomething(Class<T> dao, String id){
Properties proFind = new Properties();
proFind.put(StudentDao.ID, id);
dao.select(proFind).get(0);
return somethingINeed;
}
but this is not correct.
So my objective is to pass any Dao in that method. Did i miss something in java? Any idea or enlightenment is greatly appreciated.
[EDIT]
All my Daos extends Dao which is and interface. My concern is just this method in which how I can use any Dao. The attributes used can be found in the interface Dao also.
I agree with Kayaman's comment above.
Your service/business tier should be interfacing with multiple DAOs to perform CRUD operations on different entities eg Student, Teacher.
public class MyService {
private StudentDao studentDao;
private TeacherDao teacherDao;
// Daos injected
public Student findStudent(Long id) {
return this.studentDao.find(id);
}
// Other methods involving students or teachers
}
Trying to have one generic DAO is cumbersome and not good design in my opinion.
If you have a base DAO and base entity classes, you can still push a lot of the boilerplate CRUD code into the base classes. When I first started using DAOs, I found the following article very useful: Don't repeat the DAO!
thats why java created Interface enter link description here or Inheritance
just create a DAO interface or base class and change your method to
public static String getSomething(Dao dao, String id)
Use this
public static String getSomething(Object dao, String id){
if(dao instanceOf StudentDao){
// do your code
}
else if(dao instanceOf AnotherDao){
// do your code
}
and so on.............
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.