From a4d7c9c13a65ea6a20ee34957237069bcf223406 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20S=C3=A4ume?= Date: Wed, 22 May 2024 11:56:53 +0200 Subject: [PATCH] #27: WIP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Dominik Säume --- .idea/dataSources.xml | 2 +- db/nursingHome.db | Bin 57344 -> 61440 bytes .../nhplus/fixtures/MedicationFixture.java | 185 ++++++++++-------- .../medication/AllMedicationController.java | 20 +- .../hitec/nhplus/medication/Medication.java | 22 ++- .../nhplus/medication/MedicationListCell.java | 25 ++- .../medication/MedicationModalController.java | 23 ++- .../medication/database/MedicationDao.java | 135 ++++++++++--- .../database/Medication_Alternative.sql | 7 + 9 files changed, 303 insertions(+), 116 deletions(-) create mode 100644 src/main/resources/de/hitec/nhplus/medication/database/Medication_Alternative.sql diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml index 98f48a2..fed79a7 100644 --- a/.idea/dataSources.xml +++ b/.idea/dataSources.xml @@ -1,7 +1,7 @@ - + sqlite.xerial true org.sqlite.JDBC diff --git a/db/nursingHome.db b/db/nursingHome.db index b89b1465940bb9f8aa1e08321a549d20da8681fd..a77aae44f99b65b721a95aaa2f7331579c8824da 100644 GIT binary patch delta 1701 zcmZux4^R|U7~gkqckg!ZZXd|ufe0Lspdu(C8H1)LA(DUun3efw;}$r%+rzsBmC^%b zGQ&Y|M`tV%A*&I!K~7Ca43M!X!>}?X)3H)enTauT>NK^th^f`izTNNpz3+S9@B6b` z-T})m!P+sS=y-x45MCn}h^w3Q^hAutIve$xSp-Km65Jl{uD(tC0h`OL)y!2d(HQ9v zbr9J|4NxtfIG;cgR_gR}Hxmvxd62oLN>XGnDmzzQ2Fx9dj(QjSJv_h@L|0KC`U16M`~~FJzoOOV!yqu?M57wQ2*eVnOCS+b03XUUq*+m- zMO-lSKH&o%6+yu7f=`a1T~=z z$b|&-5=ukyC>$Z~4{ng_=5Sgqeu0pQ`S+>10LX-5A`f`5xZ42T zA(R`750^3oip&wjXhKmGI~`uiC$7j09*ZvIOG3bq%DxKSB+zYi)8pGQfb^6K0zi`_ zz}s|d@vEG>{M*KT?A80-A%{(k-h;l8?%Z z4za;)x~h`4i>;Rz8&-DS^Z$Ncz9uPx>9-u~*^&_4vZnFnmO83$Iwf=-T=Jv3_M_H2 z?@ms#L7E6muh6Z;e;0fQ{&c6)r+TYB;2YB$3BPYGcV}ePq}KeoT^Lx~6Y1^O)z_a0 zsH(nLGjM#!wZ_YK-aKzZWoXv$w7@gU#DIH?RMWC?>uv={58gH@h!wjNaiz z9nqHu=bY+1-&3Tb2_p_?$D_jUOgW#Ha3DVChWU7StZQ5VFY!+%-ESOHD=;b-AS5gfV>3qdVG7Yqq;0g_I|C!kTNGDkeX6@ GulgICqcW!e delta 1887 zcmZ9N4RF)u8OQZn@~cRS_1f6M4IwyA1_><&+r(M;7$Hdmg$0u}(Db^Gt4KtwT9z_d z`DCqQ7y5B+uSrzsN^dObNML1!4wsLWLRr&|afET@2rca~*azIm7`M?YUCY|-l@okD z?0fI@JpSqb{GaF1S-qFZ-s5E7jA={`K@dDXQy*}ve_pT*XXk4}Hux}Mvy2h^o*a#S z74D@Y>^Uef@53VN->JXZj#$Qi-M_*@ZFZ$r8@st#z>+?}eFmr$k$PYN%>a~9fUeM? z)Jo`HRbqJQS;jf*v>Y~+T9Hj~aGH&W!vvG5UY)w%D5RJ3x%9wPCRvfHHU!!Qa*Pi8 zHJGY_?j?Cxs?Zr|kBb_^oxKA#rj{E?X55mhN;k1#Y$7*RXY8bkfz3EUU89mcsanGe z=L61YfTuYAD{zf=dpzLjd}ANy&N#0EMuqKhzOimyQFwiQJv%okr&by7+NJ|*`n;_a zxCsJ~?t%jFWRotyZkVy0lpmi&jPthff#oxE*kf!L{x+t)_62OBgl7l6dVNSA$%md~YD3*fev1ATp67o`nN;7eo|)j6a5lx06qJIhrVNdy#XEsKlEi z3)hKpePLkHqDr4X;PWpG`uzdC63;h~pos*tNYF%zXsnWlRT?IZn@E-j1TZlh(uAh~ z6Lqo_7dD7`WXVw*eHvwq89X5 z20|gjsQPi5YOvaUSJ6jk3>`u{P#@ZaM6?dAM3tx*vHa)!Klro!@A$*~2;a|d<~w-- zw>z6pRA3v0B`!A!d~l7>s)%u^Jr>tRK@)UtItdD3qdvM*i;7&H8Pp3=U5$%Q7YXiz zO@g*j&?H3>bPeBScamVXwK^*F;8nG@$6^vU4c}wEBj7NDDFL^g1PiV8VxmLUBi)+X zl~rL83G%5XA&%GR;7L$Q)rd+@w=Bp}HKNMXZ6pX#b&A?0w3)Si;mP8zT-*V9cLz3( z1Rky4J26{^(nO)}Gy^A3VyH-u%lW z2fnWCI^zpm@XD0Z&`Q8KJcRSbbdT`)hdpqC$+B=ay{^T#`gkNgfzIkwC=e*r7QE5g3kZ|H^ z?JX*t_wN^fQ~Z2o@3yr^pX&RVI=*G+Hf7uO?Q5SO1Fk&bs%`JZTP1bUWu@)vrrNrR z?_SambsYKXiMfYH>`lv#@7eu8xOCSovG`N!KaV+fTpRR0^IW&@e zmUwN@Uc{Pz)pmkFw=-`#^KEzM*zh%zcJv-W#wYujnK+s`IdT$TIx^$15Cla6hT8uo eRRl9KU!)zECs2Qb)%fBPH<`LUm7=XCYxzGHxIL=? diff --git a/src/main/java/de/hitec/nhplus/fixtures/MedicationFixture.java b/src/main/java/de/hitec/nhplus/fixtures/MedicationFixture.java index 8dc9f96..cc5b57d 100644 --- a/src/main/java/de/hitec/nhplus/fixtures/MedicationFixture.java +++ b/src/main/java/de/hitec/nhplus/fixtures/MedicationFixture.java @@ -1,17 +1,17 @@ package de.hitec.nhplus.fixtures; -import de.hitec.nhplus.Main; -import de.hitec.nhplus.datastorage.DaoFactory; -import de.hitec.nhplus.medication.Ingredient; -import de.hitec.nhplus.medication.Medication; -import de.hitec.nhplus.medication.database.MedicationDao; - import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.SQLException; import java.util.*; +import de.hitec.nhplus.Main; +import de.hitec.nhplus.datastorage.DaoFactory; +import de.hitec.nhplus.medication.Ingredient; +import de.hitec.nhplus.medication.Medication; +import de.hitec.nhplus.medication.database.MedicationDao; + /** * {@link Fixture} for {@link Medication}. * @@ -20,11 +20,13 @@ import java.util.*; public class MedicationFixture implements Fixture { private static final String SCHEMA = "/de/hitec/nhplus/medication/database/Medication.sql"; private static final String INGREDIENT_SCHEMA = "/de/hitec/nhplus/medication/database/Medication_Ingredient.sql"; + private static final String ALTERNATIVE_SCHEMA = "/de/hitec/nhplus/medication/database/Medication_Alternative.sql"; @Override public void dropTable(Connection connection) throws SQLException { connection.createStatement().execute("DROP TABLE IF EXISTS medication"); - connection.createStatement().execute("DROP TABLE IF EXISTS medication_ingredient"); + connection.createStatement().execute("DROP TABLE IF EXISTS medication_ingredient"); + connection.createStatement().execute("DROP TABLE IF EXISTS medication_alternative"); } @Override @@ -32,16 +34,25 @@ public class MedicationFixture implements Fixture { final InputStream schema = Main.class.getResourceAsStream(SCHEMA); final InputStream ingredientSchema = Main.class.getResourceAsStream(INGREDIENT_SCHEMA); + final InputStream alternativeSchema = Main.class.getResourceAsStream(ALTERNATIVE_SCHEMA); + assert schema != null; assert ingredientSchema != null; + assert alternativeSchema != null; + String SQL = new Scanner(schema, StandardCharsets.UTF_8) - .useDelimiter("\\A") - .next(); + .useDelimiter("\\A") + .next(); String ingredientSQL = ";" + new Scanner(ingredientSchema, StandardCharsets.UTF_8) - .useDelimiter("\\A") - .next(); + .useDelimiter("\\A") + .next(); + String alternativeSQL = ";" + new Scanner(alternativeSchema, StandardCharsets.UTF_8) + .useDelimiter("\\A") + .next(); + connection.createStatement().execute(SQL); connection.createStatement().execute(ingredientSQL); + connection.createStatement().execute(alternativeSQL); } @@ -67,86 +78,106 @@ public class MedicationFixture implements Fixture { Ingredient warfarinnatrium = new Ingredient("Warfarinnatrium"); medications.add(new Medication( - "Metformin", - "AstraZeneca", - List.of( - metforminhydrochlorid, - cellulose, - povidon, - magnesiumstearat - ), - "Übelkeit, Durchfall, Laktatazidose (selten)", - "Oral", - 100 + "Metformin", + "AstraZeneca", + List.of( + metforminhydrochlorid, + cellulose, + povidon, + magnesiumstearat + ), + "Übelkeit, Durchfall, Laktatazidose (selten)", + "Oral", + 100, + new ArrayList<>() )); medications.add(new Medication( - "Lisinopril", - "Teva Pharmaceuticals", - List.of( - lisinoprilDihydrat, - mannitol, - calciumphosphat, - magnesiumstearat - ), - "Schwindel, trockener Husten", - "Oral", - 150 + "Lisinopril", + "Teva Pharmaceuticals", + List.of( + lisinoprilDihydrat, + mannitol, + calciumphosphat, + magnesiumstearat + ), + "Schwindel, trockener Husten", + "Oral", + 150, + new ArrayList<>() )); medications.add(new Medication( - "Simvastatin", - "Mylan", - List.of( - simvastatin, - laktose, - cellulose, - magnesiumstearat - ), - "Muskelschmerzen, Leberprobleme(selten)", - "Oral", - 80 + "Simvastatin", + "Mylan", + List.of( + simvastatin, + laktose, + cellulose, + magnesiumstearat + ), + "Muskelschmerzen, Leberprobleme(selten)", + "Oral", + 80, + new ArrayList<>() )); medications.add(new Medication( - "Enoxaparin", - "Sanofi", - List.of( - enoxaparinNatrium, - benzylalkohol, - wasser - ), - "Blutungen, Reaktionen an der Injektionsstelle", - "Unterhautinjektion", - 120 + "Enoxaparin", + "Sanofi", + List.of( + enoxaparinNatrium, + benzylalkohol, + wasser + ), + "Blutungen, Reaktionen an der Injektionsstelle", + "Unterhautinjektion", + 120, + new ArrayList<>() )); medications.add(new Medication( - "Levothyroxin", - "Sandoz", - List.of( - levothyroxinnatrium, - laktose, - staerke, - akaziengummi - ), - "Herzrasen, Gewichtsverlust", - "Oral", - 90 + "Levothyroxin", + "Sandoz", + List.of( + levothyroxinnatrium, + laktose, + staerke, + akaziengummi + ), + "Herzrasen, Gewichtsverlust", + "Oral", + 90, + new ArrayList<>() )); medications.add(new Medication( - "Warfarin", - "Apotex Inc.", - List.of( - warfarinnatrium, - laktose, - staerke, - magnesiumstearat - ), - "Blutungen, Blutergüsse", - "Oral", - 110 + "Warfarin", + "Apotex Inc.", + List.of( + warfarinnatrium, + laktose, + staerke, + magnesiumstearat + ), + "Blutungen, Blutergüsse", + "Oral", + 110, + new ArrayList<>() )); MedicationDao dao = DaoFactory.getInstance().createMedicationDAO(); - Map medicationsByName = new HashMap<>(); for (Medication medication : medications) { dao.create(medication); + } + List createdMedications = dao.readAll(); + Map medicationsByName = new HashMap<>(); + for (Medication medication : createdMedications){ + switch (medication.getName()){ + case "Warfarin": + medication.setAlternativeMedication(List.of( + createdMedications.get(0), + createdMedications.get(3) + )); + break; + default: + break; + } + dao.update(medication); medicationsByName.put(medication.getName(), medication); } return medicationsByName; diff --git a/src/main/java/de/hitec/nhplus/medication/AllMedicationController.java b/src/main/java/de/hitec/nhplus/medication/AllMedicationController.java index 070c582..4af118a 100644 --- a/src/main/java/de/hitec/nhplus/medication/AllMedicationController.java +++ b/src/main/java/de/hitec/nhplus/medication/AllMedicationController.java @@ -48,6 +48,8 @@ public class AllMedicationController { private TableColumn columnAdministrationMethod; @FXML private TableColumn columnCurrentStock; + @FXML + public TableColumn columnAlternativeMedication; private final ObservableList medications = FXCollections.observableArrayList(); private MedicationDao dao; @@ -77,13 +79,29 @@ public class AllMedicationController { return new SimpleStringProperty( ingredients .stream() - .map(ingredient -> ingredient.getName()) + .map(Ingredient::getName) .collect(Collectors.joining("\n")) ); }); this.columnPossibleSideEffects.setCellValueFactory(new PropertyValueFactory<>("possibleSideEffects")); this.columnAdministrationMethod.setCellValueFactory(new PropertyValueFactory<>("administrationMethod")); this.columnCurrentStock.setCellValueFactory(new PropertyValueFactory<>("currentStock")); + this.columnAlternativeMedication.setCellValueFactory( + cellData -> { + Medication medication = cellData.getValue(); + List alternatives = medication.getAlternativeMedication(); + if (alternatives.isEmpty()) { + return new SimpleStringProperty(""); + } + + return new SimpleStringProperty( + alternatives + .stream() + .map(med -> med.getName() + ", " + med.getManufacturer()) + .collect(Collectors.joining("\n")) + ); + } + ); this.tableView.setItems(this.medications); } diff --git a/src/main/java/de/hitec/nhplus/medication/Medication.java b/src/main/java/de/hitec/nhplus/medication/Medication.java index 7fdce57..db4f595 100644 --- a/src/main/java/de/hitec/nhplus/medication/Medication.java +++ b/src/main/java/de/hitec/nhplus/medication/Medication.java @@ -23,6 +23,7 @@ public class Medication { private final SimpleStringProperty possibleSideEffects; private final SimpleStringProperty administrationMethod; private final SimpleIntegerProperty currentStock; + private final SimpleListProperty alternativeMedication; /** * This constructor allows instantiating a {@link Medication} object, @@ -37,7 +38,8 @@ public class Medication { List ingredients, String possibleSideEffects, String administrationMethod, - int currentStock + int currentStock, + List alternativeMedication ) { this.name = new SimpleStringProperty(name); this.manufacturer = new SimpleStringProperty(manufacturer); @@ -45,6 +47,7 @@ public class Medication { this.possibleSideEffects = new SimpleStringProperty(possibleSideEffects); this.administrationMethod = new SimpleStringProperty(administrationMethod); this.currentStock = new SimpleIntegerProperty(currentStock); + this.alternativeMedication = new SimpleListProperty<>(FXCollections.observableArrayList(alternativeMedication)); } /** @@ -57,7 +60,8 @@ public class Medication { List ingredients, String possibleSideEffects, String administrationMethod, - int currentStock + int currentStock, + List alternativeMedication ) { this.id = new SimpleIntegerProperty(id); this.name = new SimpleStringProperty(name); @@ -66,6 +70,7 @@ public class Medication { this.possibleSideEffects = new SimpleStringProperty(possibleSideEffects); this.administrationMethod = new SimpleStringProperty(administrationMethod); this.currentStock = new SimpleIntegerProperty(currentStock); + this.alternativeMedication = new SimpleListProperty<>(FXCollections.observableArrayList(alternativeMedication)); } public int getId() { @@ -124,6 +129,18 @@ public class Medication { this.possibleSideEffects.set(possibleSideEffects); } + public ObservableList getAlternativeMedication() { + return alternativeMedication.get(); + } + + public SimpleListProperty alternativeMedicationProperty() { + return alternativeMedication; + } + + public void setAlternativeMedication(List alternativeMedication) { + this.alternativeMedication.set(FXCollections.observableArrayList(alternativeMedication)); + } + public String getAdministrationMethod() { return administrationMethod.get(); } @@ -162,6 +179,7 @@ public class Medication { .add("Possible Side Effects: " + this.getPossibleSideEffects()) .add("Administration Method: " + this.getAdministrationMethod()) .add("Current Stock: " + this.getCurrentStock()) + .add("Alternative Medication" + this.getAlternativeMedication()) .toString(); } diff --git a/src/main/java/de/hitec/nhplus/medication/MedicationListCell.java b/src/main/java/de/hitec/nhplus/medication/MedicationListCell.java index 608267b..fffbc25 100644 --- a/src/main/java/de/hitec/nhplus/medication/MedicationListCell.java +++ b/src/main/java/de/hitec/nhplus/medication/MedicationListCell.java @@ -21,20 +21,19 @@ import org.controlsfx.control.SearchableComboBox; */ public class MedicationListCell extends ListCell { private final Button deleteButton; - private SearchableComboBox comboBox; + private final SearchableComboBox comboBox; private static final double BUILTIN_BORDER_WIDTH = 1; private static final double CELL_SPACING = 4; private static final double CELL_PADDING = 4; private static final double BUTTON_PADDING_X = 8; private static final double BUTTON_PADDING_Y = 4; private final double totalSpacing; - private final List allOtherMedications; + private boolean firstUpdate = true; public MedicationListCell(List allOtherMedications) { - this.allOtherMedications = allOtherMedications; this.setPadding(new Insets(CELL_PADDING)); - comboBox = new SearchableComboBox(); + comboBox = new SearchableComboBox<>(); ObservableList list = FXCollections.observableArrayList(); list.setAll(allOtherMedications); comboBox.setItems(list); @@ -68,7 +67,15 @@ public class MedicationListCell extends ListCell { Medication oldValue, Medication newValue ) { + Medication selectedMedication = comboBox.getValue(); ListView listView = getListView(); + + if(oldValue != null) { + listView.getItems().remove(getItem()); + listView.getItems().add(selectedMedication); + setItem(selectedMedication); + } + double max = listView.lookupAll("*") .stream() .filter(node -> node instanceof MedicationListCell) @@ -86,6 +93,16 @@ public class MedicationListCell extends ListCell { if (empty || item == null) { setGraphic(null); } else { + if( + firstUpdate + && comboBox.getSelectionModel().getSelectedItem() == null + && item.getName() != null + && comboBox.getItems().contains(item) + ) { + comboBox.getSelectionModel().select(item); + } + firstUpdate = false; + BorderPane cellPane = new BorderPane(); cellPane.setCenter(comboBox); cellPane.setRight(deleteButton); diff --git a/src/main/java/de/hitec/nhplus/medication/MedicationModalController.java b/src/main/java/de/hitec/nhplus/medication/MedicationModalController.java index fa89b39..00885e5 100644 --- a/src/main/java/de/hitec/nhplus/medication/MedicationModalController.java +++ b/src/main/java/de/hitec/nhplus/medication/MedicationModalController.java @@ -4,7 +4,9 @@ import static de.hitec.nhplus.utils.Validator.*; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.function.Predicate; +import java.util.stream.Collectors; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; @@ -70,7 +72,8 @@ public class MedicationModalController { new ArrayList<>(), "", "", - 0 + 0, + new ArrayList<>() ); this.buttonSave.setDisable(true); } @@ -103,12 +106,17 @@ public class MedicationModalController { */ private void showData() { ingredients.setAll(medication.getIngredients()); + alternativeMediaction.setAll(medication.getAlternativeMedication()); + Map currentAlternatives = alternativeMediaction + .stream() + .collect(Collectors.toMap(Medication::getId, med -> med)); try { allOtherMedications = controller.getDao().readAll(); if (!isNewMedication) { allOtherMedications = allOtherMedications .stream() .filter(med -> med.getId() != medication.getId()) + .map(med -> currentAlternatives.getOrDefault(med.getId(), med)) .toList(); } } catch (Exception exception) { @@ -137,6 +145,14 @@ public class MedicationModalController { .toList() ); + List meds = alternativeMediaction + .stream() + .distinct() + .toList(); + this.medication.setAlternativeMedication( + meds + ); + if (isNewMedication) { controller.createMedication(medication); } else { @@ -161,10 +177,11 @@ public class MedicationModalController { alternativeMediaction.add(new Medication( null, null, - List.of(), + new ArrayList<>(), null, null, - -1 + -1, + new ArrayList<>() )); } } diff --git a/src/main/java/de/hitec/nhplus/medication/database/MedicationDao.java b/src/main/java/de/hitec/nhplus/medication/database/MedicationDao.java index e226770..d953114 100644 --- a/src/main/java/de/hitec/nhplus/medication/database/MedicationDao.java +++ b/src/main/java/de/hitec/nhplus/medication/database/MedicationDao.java @@ -8,10 +8,7 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** * The {@link MedicationDao} is an implementation of the{@link de.hitec.nhplus.datastorage.Dao Dao} @@ -63,36 +60,45 @@ public class MedicationDao implements Dao { ingredientStatement.setString(2, ingredient.getName()); ingredientStatement.execute(); } + + final String alternativeMedicationSQL = """ + INSERT INTO medication_alternative + (id, alternativeId) + VALUES (?, ?); + """; + for (Medication alternative : medication.getAlternativeMedication()) { + PreparedStatement alternativeStatement = this.connection.prepareStatement(alternativeMedicationSQL); + alternativeStatement.setInt(1, newId); + alternativeStatement.setInt(2, alternative.getId()); + alternativeStatement.execute(); + } } @Override public Medication read(int id) throws SQLException { - final String SQL = """ - SELECT medication.*, medication_ingredient.id - FROM medication - LEFT JOIN medication_ingredient ON medication.id = medication_ingredient.id - WHERE medication.id = ? - """; - PreparedStatement statement = this.connection.prepareStatement(SQL); - statement.setInt(1, id); - ResultSet result = statement.executeQuery(); + ResultSet result = getReadStatement(id).executeQuery(); return getInstanceFromResultSet(result); } @Override public List readAll() throws SQLException { final String SQL = """ - SELECT medication.*, medication_ingredient.name - FROM medication LEFT JOIN + SELECT medication.*, medication_ingredient.name, medication_alternative.alternativeId + FROM medication + LEFT JOIN medication_ingredient ON medication.id = medication_ingredient.id + LEFT JOIN + medication_alternative ON medication.id = medication_alternative.id """; ResultSet result = connection.prepareStatement(SQL).executeQuery(); - List medications = new ArrayList<>(); + Map medications = new HashMap<>(); Map> ingredientMap = new HashMap<>(); + Map> alternativesMap = new HashMap<>(); int currentMedicationId; int lastMedicationId = -1; + String latIngredient = ""; while (result.next()) { currentMedicationId = result.getInt(1); if (currentMedicationId != lastMedicationId) { @@ -103,27 +109,42 @@ public class MedicationDao implements Dao { new ArrayList<>(), result.getString(4), result.getString(5), - result.getInt(6) + result.getInt(6), + new ArrayList<>() ); - medications.add(medication); + medications.put(currentMedicationId, medication); } + List ingredients = ingredientMap.computeIfAbsent(currentMedicationId, k -> new ArrayList<>()); String ingredientName = result.getString(7); - if(ingredientName == null){ - continue; + if (ingredientName != null && !latIngredient.equals(ingredientName)) { + ingredients.add(new Ingredient(ingredientName)); + latIngredient = ingredientName; } - ingredients.add(new Ingredient(ingredientName)); + + Set alternatives = alternativesMap.computeIfAbsent(currentMedicationId, k -> new HashSet<>()); + int alternativeId = result.getInt(8); + if (alternativeId != 0) { + alternatives.add(alternativeId); + } + lastMedicationId = currentMedicationId; } - for (Medication medication : medications) { + for (Medication medication : medications.values()) { List ingredients = ingredientMap.get(medication.getId()); - if(ingredients.isEmpty()){ + if (ingredients.isEmpty()) { continue; } medication.setIngredients(ingredientMap.get(medication.getId())); + Set alternativeIds = alternativesMap.get(medication.getId()); + List alternatives = new ArrayList<>(); + for (Integer alternativeId : alternativeIds) { + alternatives.add(medications.get(alternativeId)); + } + medication.setAlternativeMedication(alternatives); } - return medications; + return medications.values().stream().toList(); } @Override @@ -164,6 +185,25 @@ public class MedicationDao implements Dao { statement.setString(2, ingredient.getName()); statement.execute(); } + + final String alternativeDeleteSQL = """ + DELETE FROM medication_alternative WHERE id = ? + """; + PreparedStatement alternativeStatement = this.connection.prepareStatement(alternativeDeleteSQL); + alternativeStatement.setInt(1, medication.getId()); + alternativeStatement.executeUpdate(); + + final String alternativeCreateSQL = """ + INSERT INTO medication_alternative + (id, alternativeId) + VALUES (?, ?); + """; + for (Medication alternative : medication.getAlternativeMedication()) { + PreparedStatement statement = this.connection.prepareStatement(alternativeCreateSQL); + statement.setInt(1, medication.getId()); + statement.setInt(2, alternative.getId()); + statement.execute(); + } } @Override @@ -176,6 +216,23 @@ public class MedicationDao implements Dao { preparedStatement.executeUpdate(); } + /** + * @param id The ID of the database entry to read. + * @return A {@link PreparedStatement} to read a specific entry by its ID. + */ + public PreparedStatement getReadStatement(int id) throws SQLException { + final String SQL = """ + SELECT medication.*, medication_ingredient.name, medication_alternative.alternativeId + FROM medication + LEFT JOIN medication_ingredient ON medication.id = medication_ingredient.id + LEFT JOIN medication_alternative ON medication.id = medication_alternative.id + WHERE medication.id = ? + """; + PreparedStatement statement = this.connection.prepareStatement(SQL); + statement.setInt(1, id); + return statement; + } + /** * Constructs a {@link Medication} object from the {@link ResultSet} obtained after executing a database query. * This method is used internally to map the {@link ResultSet} data to a {@link Medication} object. @@ -188,18 +245,40 @@ public class MedicationDao implements Dao { result.getInt(1), result.getString(2), result.getString(3), - List.of(), + new ArrayList<>(), result.getString(4), result.getString(5), - result.getInt(6) + result.getInt(6), + new ArrayList<>() ); List ingredients = new ArrayList<>(); + List alternatives = new ArrayList<>(); while (result.next()) { - ingredients.add(new Ingredient(result.getString(2))); - + String ingredientName = result.getString(7); + if (ingredientName != null) { + ingredients.add(new Ingredient(ingredientName)); + } + int alternativeId = result.getInt(8); + if (alternativeId != 0) { + ResultSet alternativeResult = getReadStatement(alternativeId).executeQuery(); + Medication alternativeMedication = new Medication( + alternativeResult.getInt(1), + alternativeResult.getString(2), + alternativeResult.getString(3), + new ArrayList<>(), + alternativeResult.getString(4), + alternativeResult.getString(5), + alternativeResult.getInt(6), + new ArrayList<>() + ); + alternatives.add(alternativeMedication); + } } medication.setIngredients(ingredients); + medication.setAlternativeMedication(alternatives); return medication; + + } } diff --git a/src/main/resources/de/hitec/nhplus/medication/database/Medication_Alternative.sql b/src/main/resources/de/hitec/nhplus/medication/database/Medication_Alternative.sql new file mode 100644 index 0000000..76e3364 --- /dev/null +++ b/src/main/resources/de/hitec/nhplus/medication/database/Medication_Alternative.sql @@ -0,0 +1,7 @@ +CREATE TABLE medication_alternative +( + id INTEGER NOT NULL , + alternativeId INTEGER NOT NULL , + FOREIGN KEY (id) REFERENCES medication (id) ON DELETE CASCADE, + FOREIGN KEY (alternativeId) REFERENCES medication (id) ON DELETE CASCADE +) \ No newline at end of file