Programación

1º DAM/DAW - Curso 2023-2024

User Tools

Site Tools


apuntes:dao

Aplicación que conecta con Base de datos. Patrón DAO

Patrón DAO

Librería Jdbi 3

Creación de un DAO con Jdbi

@Data
@RequiredArgsConstructor
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Vehicle {
 
  private int id;
  @NonNull
  private String licensePlate;
  @NonNull
  private String brand;
  @NonNull
  private String model;
  @NonNull
  private int kilometers;
  @NonNull
  private String image;
  @NonNull
  private LocalDate registrationDate;
}
public class Database {
 
  public static Jdbi jdbi;
  public static Handle db;
 
  public static void connect() {
    jdbi = Jdbi.create(DATABASE_URL, DATABASE_USERNAME, DATABASE_PASSWORD);
    jdbi.installPlugin(new SqlObjectPlugin());
    db = jdbi.open();
  }
 
  public static void close() {
    db.close();
  }
}
public interface VehicleDAO {
 
  @SqlQuery("SELECT * FROM vehicles")
  @UseRowMapper(VehicleMapper.class)
  List<Vehicle> getVehicles();
 
  @SqlQuery("SELECT * FROM vehicles WHERE brand = ? OR model = ?")
  @UseRowMapper(VehicleMapper.class)
  List<Vehicle> getVehicles(String search);
 
  @SqlQuery("SELECT * FROM vehicles WHERE brand = ? AND model = ?")
  @UseRowMapper(VehicleMapper.class)
  List<Vehicle> getVehicles(String brand, String model);
 
  @SqlQuery("SELECT * FROM vehicles WHERE id = ?")
  @UseRowMapper(VehicleMapper.class)
  Vehicle getVehicle(int id);
 
  @SqlUpdate("INSERT INTO vehicles (license_plate, brand, model, kilometers, image, registration_date) VALUES (?, ?, ?, ?, ?, ?)")
  void addVehicle(String licensePlate, String brand, String model, int kilometers, String image, Date registrationDate);
 
  @SqlUpdate("DELETE FROM vehicles WHERE id = ?")
  void removeVehicle(int id);
 
  @SqlUpdate("UPDATE vehicles SET license_plate = ?, brand = ?, model = ?, kilometers = ?, image = ? WHERE id = ?")
  void editVehicle(String licensePlate, String brand, String model, int kilometers, String image, int id);
 
  @SqlUpdate("UPDATE vehicles SET license_plate = ?, brand = ?, model = ?, kilometers = ? WHERE id = ?")
  void editVehicle(String licensePlate, String brand, String model, int kilometers, int id);
}
public class VehicleMapper implements RowMapper<Vehicle> {
 
  @Override
  public Vehicle map(ResultSet rs, StatementContext ctx) throws SQLException {
    return new Vehicle(rs.getInt("id"),
        rs.getString("license_plate"),
        rs.getString("brand"),
        rs.getString("model"),
        rs.getInt("kilometers"),
        rs.getString("image"),
        DateUtils.getLocalDate(rs.getDate("registration_date"))
    );
  }
}

© 2023 Santiago Faci

apuntes/dao.txt · Last modified: 2023/06/04 21:09 by Santiago Faci