Wzorzec DAO

0

Witam.

Mam model User

User {
  private int id;
  private String name;
  private String surname;
  private int age;
  
  public int getId() {
      return id;
  }
  
  public int setId(int id) {
      this.id = id;
  }
  
  public String getName() {
      return name;
  }
  
  public void setName(String name) {
      this.name = name;
  }
  
  public String getSurname() {
      return surname;
  }
  
  public void setSurname(String surname) {
      this.surname = surname;
  }
  
  public int getAge() {
      return age;
  }
  
  public void setAge(int age) {
      this.age = age;
  }
  
}

Następnie klasy DAO

  • UserDetailsDAO - posiada wszystkie dane klasy User
  • UserShortDAO - posiada tylko name i surname.

I teraz mam pytanie, czy żeby dodać metodę wyświetlającą dane (name, surname) dla klasy UserShortDAO muszę tworzyć nowy model UserShort, czy można wykorzystać bieżący. Jeśli model może być wspólny, to jak będzie wyglądać metoda wyświetlająca dane dla klasy UserShortDAO, tak żeby nie było możliwości pobranie zbędnego w tym przypadku getAge?

public class UserShortDAO {

  public User getDataShort() {
      
      String sql = "SELECT * FROM User LIMIT 0,1";
      
      Connection conn = null;
      
      try {
        conn = dataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        User user = null;
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
          user = new User();
          user.setId(rs.getInt("id"));
          user.setName(rs.getString("name"));
          user.setSurname(rs.getString("surname"));
        }
        rs.close();
        ps.close();
        return user; // jest możliwość odwołania się do metody getAge
      } catch (SQLException e) {
        throw new RuntimeException(e);
      } finally {
        if (conn != null) {
          try {
          conn.close();
          } catch (SQLException e) {}
        }
      }
  }

}

Uwaga:
Powyższy kod może mieć błędy składniowe, chodziło tylko o to żeby zobrazować problem.
Z góry dzięki za pomoc.

1

A czemu nie zrobisz po prostu z tego 2 klas? Jedna ma tylko te kilka pól a druga za pomocą kompozycji albo dziedziczenia ma dodane pozostałe pola.

0

Właśnie myślałem o takim rozwiązaniu, ale pomyślałem, że może jest inny lepszy sposób. Może ktoś jeszcze coś mądrego napisze w tym wątku. Jeśli nie, to później zamknę temat.

1 użytkowników online, w tym zalogowanych: 0, gości: 1