问题描述
我目前正在学习在项目中使用Dao
模式的方法.我知道,一张桌子等于一张Dao
,对吗?就像StudentDao
,SubjectDao
.
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 DAO
for 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 Object
是Object
,只能与数据库通信.因此,如果要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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!