#java #терминология #dto
Могли бы вы на примере несложного кода JAVA объяснить, что такое DTO? Зачем это нужно?
Будет ли являться этот код DTO? Есть два класса Customer и Bank
Customer
import java.sql.Date;
class Customer {
private String first_name;
private String last_name;
private String gedner;
private Date age;
private String address;
Customer(String first_name, String last_name, String gedner, Date age, String
address) {
this.first_name = first_name;
this.last_name = last_name;
this.gedner = gedner;
this.age = age;
this.address = address;
}
public String getLast_name() {
return last_name;
}
public String getFirst_name() {
return first_name;
}
public String getGedner() {
return gedner;
}
public Date getAge() {
return age;
}
public String getAddress() {
return address;
}
}
Bank
import java.sql.*;
import java.util.Scanner;
public class Bank {
private static final String URL = "jdbc:mysql://localhost/bank?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
private static final String USER = "root";
private static final String PASSWORD = "root";
Connection connection = null;
PreparedStatement preparedStatement = null;
Scanner in = new Scanner(System.in);
public void connect() {
try {
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
}
Customer readCustomer() {
Customer customer = null;
try {
preparedStatement = connection.prepareStatement("SELECT * FROM customers
WHERE id_customer = ?");
System.out.print("Введите id пользователя: ");
preparedStatement.setInt(1, Integer.parseInt(in.next()));
preparedStatement.execute();
ResultSet rs = preparedStatement.executeQuery();
String first_name = rs.getString("first_name");
String last_name = rs.getString("last_name");
String gender = rs.getString("gender");
Date age = rs.getDate("age");
String address = rs.getString("address");
customer = new Customer(first_name, last_name, gender, age, address);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return customer;
}
}
В методе read я превращаю ResultSet в объект customer. Это и есть DTO?
Ответы
Ответ 1
Объект Customer - DTO. DTO объект - объект, который не содержит методы. Он может содержать только поля, геттеры/сеттеры, и конструкторы. Data Transfer Object - объект, передающий данные. Данные - это и есть поля в классе. Реальный пример - игра шашки. У вас должен быть объект Checker(шашка). У него не должно быть методов, только поля. public class Checker { private COLOR checkerColor; private Coordinate coordinate; //show checker coordinate private boolean isQueen; //show is the checker queen public Checker(COLOR checkerColor, int xCoordinate, int yCoordinate) { this.checkerColor = checkerColor; coordinate = new Coordinate(xCoordinate, yCoordinate); isQueen = false; } public Checker() {} public COLOR getColor() { return checkerColor; } public Coordinate getCoordinate() { return coordinate; } public boolean isQueen() { return isQueen; } public void setCoordinate(Coordinate coordinate) { this.coordinate.setCoordinates(coordinate.getX(), coordinate.getY()); } public void setQueen() { isQueen = true; } } Или класс Cell(шашечное поле). public class Cell { private boolean isBusy; //shows does the field is occupied with the checker private Coordinate coordinate; //show field coordinate public Cell(boolean isBusy, int x, int y) { coordinate = new Coordinate(x, y); this.isBusy = isBusy; } public Cell() {} public boolean isBusy() { return isBusy; } public void setBusy(boolean isBusy) { this.isBusy = isBusy; } public Coordinate getCoordinate() { return coordinate; } } Или класс Board(доска): public class Board { private Listcells; //list with 64 Fields() private List | checkers; //list with Checkers(), whose number falls from 24 to 0 public Board() { cells = new LinkedList<>(); checkers = new LinkedList<>(); } public List getCells() { return cells; } public List | getCheckers() { return checkers; } } Или класс Coordinate. Хотя у него есть методы(переопределенный equals и compare), но это методы из Object и он тоже может считаться DTO объектом, т.к. он сделан только для того, что бы хранить данные(координаты). public class Coordinate { private int x; //x coordinate private int y; //y coordinate public Coordinate(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public void setCoordinates(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Coordinate that = (Coordinate) o; return x == that.x && y == that.y; } public boolean compare(Coordinate that, int xMove, int yMove) { return x == that.getX() + xMove && y == that.getY() + yMove; }
Комментариев нет:
Отправить комментарий