本文介绍了如何为联接表创建DAO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习在项目中使用Dao模式的方法.我知道,一张桌子等于一张Dao,对吗?就像StudentDaoSubjectDao.

I'm currently on learning on using Dao pattern in my project. I know, one Table is equivalent to one Dao, am I right? just like StudentDao, SubjectDao.

每个Dao在其关联表中执行CRUD操作,但是我的问题是,如何为联接表创建DAO?可以说我有一个查询来连接学生表和主题表,然后如何为此创建一个DAO呢?

Each Dao performs CRUD operations in their associated tables, but my question is, how am I going to create a DAO for joined tables? lets say I have a query to join student and subject table, then how do I create a DAOfor that?

我应该将其放置在StudentDao上吗?还是SubjectDao?或在这种情况下有好的做法?

Should I place it to the StudentDao? or to SubjectDao? or there's a good practice in that kind of situation?

推荐答案

DAO - Data Access ObjectObject,只能与数据库通信.因此,如果要JOIN两个表,则必须在SubjectDTO上的DTO Object StudentDTO参考中.

DAO - Data Access Object is Object that should only communicate with database. So if you want to JOIN two tables so you must have in your DTO Object StudentDTO reference on SubjectDTO.

public class StudentDTO {

   private String name;
   private String surname;
   private String age;
   private SubjectDTO subject;

  // getters, setters
}

因此,SubjectDTO

So, SubjectDTO

public class SubjectDTO {

   private String name;
   private int room;

  // getters, setters
}

DAO看起来像这样:

public StudentDAO {

   private final String SELECT_QUERY = "SELECT * FROM Student S JOIN Subject Sb ON (S.id = Sb.id)"

   public ArrayList<StudentDTO> getData() {

      ArrayList<StudentDTO> data = null;
      StudentDTO member = null;
      Connection con = null;
      PreparedStatement ps = null;
      ResultSet rs = null;

      try {
         con = OracleDAOFactory.getConnection();
         ps = con.prepareStatement(SELECT_QUERY);
         rs = ps.executeQuery();
         while (rs.next()) {
            member = new StudentDTO();
            member.setName(rs.getString(1));
            ...
            data.add(member);
         }
         return data;
      }
      catch (SQLException ex) {
         // body
      }
      finally {
         if (con != null) {
            con.close();
         }
      }
   }
}

我建议您查看一些教程.

I recommend to you check some tutorials.

致谢

这篇关于如何为联接表创建DAO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 09:04
查看更多