How to create a DAO for join tables?

I am currently studying the use of the Dao pattern in my project. I know that one table is equivalent to one Dao , right? just like StudentDao , SubjectDao .

Each Dao performs CRUD operations on related tables, but my question is: how will I create Dao for joined tables? let's say I have a request to join a student and subject table, then how do I create a Dao for this?

Should I put it in StudentDao ? or SubjectDao ? or is there good practice in such a situation?

+8
join dao table
source share
2 answers

DAO - Data Access Object - Object , which should only support communication with the database. Therefore, if you want JOIN two tables, so you should have a link to the DTO Object StudentDTO on SubjectDTO .

 public class StudentDTO { private String name; private String surname; private String age; private SubjectDTO subject; // getters, setters } 

So SubjectDTO

 public class SubjectDTO { private String name; private int room; // getters, setters } 

And the DAO might look like this:

 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 you check out some of the lessons.

Hi

+9
source share

This thread is already running on javaRanch (JDBC), you want to check if you will lose your efforts before responding to the first

-4
source share

All Articles