diff --git a/BerlinAIT/Cohort42.1project/JavaPizzaMvn/src/main/java/pizza/domain/ExtComponent.java b/BerlinAIT/Cohort42.1project/JavaPizzaMvn/src/main/java/pizza/domain/ExtComponent.java index 38974b92..3d0004e4 100644 --- a/BerlinAIT/Cohort42.1project/JavaPizzaMvn/src/main/java/pizza/domain/ExtComponent.java +++ b/BerlinAIT/Cohort42.1project/JavaPizzaMvn/src/main/java/pizza/domain/ExtComponent.java @@ -4,7 +4,7 @@ * Extra (additional) component to pizza * * @author Sergey Iryupin - * @version 13-May-24 + * @version 30-Jun-24 */ public class ExtComponent { private Integer id; @@ -25,6 +25,14 @@ public void setId(Integer id) { this.id = id; } + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + public void update(String name, int price) { this.name = name; this.price = price; diff --git a/BerlinAIT/Cohort42.1project/JavaPizzaMvn/src/main/java/pizza/repository/db/ExtComponentDbRepository.java b/BerlinAIT/Cohort42.1project/JavaPizzaMvn/src/main/java/pizza/repository/db/ExtComponentDbRepository.java index 6036a572..42999ac9 100644 --- a/BerlinAIT/Cohort42.1project/JavaPizzaMvn/src/main/java/pizza/repository/db/ExtComponentDbRepository.java +++ b/BerlinAIT/Cohort42.1project/JavaPizzaMvn/src/main/java/pizza/repository/db/ExtComponentDbRepository.java @@ -3,6 +3,12 @@ import pizza.domain.ExtComponent; import pizza.repository.CrudRepository; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; import java.util.Collection; /** @@ -10,7 +16,7 @@ * Implementation of access methods to the ExtComponent data source * * @author Sergey Iryupin - * @version 23-Jun-24 + * @version 30-Jun-24 */ public class ExtComponentDbRepository implements CrudRepository { @@ -35,8 +41,31 @@ public ExtComponentDbRepository(String dbName) { } @Override - public ExtComponent save(ExtComponent value) { - return null; + public ExtComponent save(ExtComponent component) { + try (Connection connection = DriverManager.getConnection(dbName); + PreparedStatement psi = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS); + PreparedStatement psu = connection.prepareStatement(SQL_UPDATE)) { + if (component.getId() == null) { + // insert record + psi.setString(1, component.getName()); + psi.setInt(2, component.getPrice()); + psi.executeUpdate(); + + ResultSet rs = psi.getGeneratedKeys(); + if (rs.next()) { + component.setId(rs.getInt(1)); + } + } else { + // update record + psi.setString(1, component.getName()); + psi.setInt(2, component.getPrice()); + psu.setInt(3, component.getId()); + psu.executeUpdate(); + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + return component; } @Override