简体   繁体   English

Java-传递未知的DAO

[英]Java- Passing unknown DAO

I created a common method in which I will pass a DAO but it will not be a one DAO. 我创建了一种通用方法,在该方法中我将传递一个DAO,但不会成为一个DAO。 Like i will be passing not only StudentDao but also TeachersDao and ClubsDao. 就像我将不仅通过StudentDao,还将通过TeachersDao和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. 因此,我的目标是通过该方法传递任何Dao。 Did i miss something in java? 我错过了Java吗? Any idea or enlightenment is greatly appreciated. 任何想法或启示都将不胜感激。

[EDIT] [编辑]

All my Daos extends Dao which is and interface. 我所有的Dao都扩展了Dao,它是and接口。 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. 所使用的属性也可以在Dao界面中找到。

I agree with Kayaman's comment above. 我同意上面Kayaman的评论。

Your service/business tier should be interfacing with multiple DAOs to perform CRUD operations on different entities eg Student, Teacher. 您的服务/业务层应与多个DAO交互,以对不同实体(例如,学生,教师)执行CRUD操作。

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. 在我看来,尝试拥有一个通用的DAO既麻烦又不好。

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. 如果您有基DAO和基实体类,则仍可以将许多样板CRUD代码推入基类。 When I first started using DAOs, I found the following article very useful: Don't repeat the DAO! 当我第一次开始使用DAO时,我发现以下文章非常有用: 不要重复DAO!

thats why java created Interface enter link description here or Inheritance 多数民众赞成为什么Java创建的接口在此处继承中 输入链接描述

just create a DAO interface or base class and change your method to 只需创建一个DAO接口或基类,然后将您的方法更改为

public static String getSomething(Dao dao, String id) 公共静态字符串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............. 等等.............

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM