#22: Setup Model and DAO
All checks were successful
Quality Check / Qualty Check (push) Successful in 8s

Signed-off-by: Dominik Säume <Dominik.Saeume@hmmh.de>
This commit is contained in:
Dominik Säume 2024-05-06 14:29:26 +02:00
parent 40a9a793cd
commit bbbb569b55
Signed by: SZUT-Dominik
GPG key ID: 67D15BB250B41E7C
15 changed files with 529 additions and 11 deletions

View file

@ -25,6 +25,8 @@
<option value="file://$PROJECT_DIR$/src/main/resources/de/hitec/nhplus/patient/database/Patient.sql" /> <option value="file://$PROJECT_DIR$/src/main/resources/de/hitec/nhplus/patient/database/Patient.sql" />
<option value="file://$PROJECT_DIR$/src/main/resources/de/hitec/nhplus/treatment/database/Treatment.sql" /> <option value="file://$PROJECT_DIR$/src/main/resources/de/hitec/nhplus/treatment/database/Treatment.sql" />
<option value="file://$PROJECT_DIR$/src/main/resources/de/hitec/nhplus/nurse/database/Nurse.sql" /> <option value="file://$PROJECT_DIR$/src/main/resources/de/hitec/nhplus/nurse/database/Nurse.sql" />
<option value="file://$PROJECT_DIR$/src/main/resources/de/hitec/nhplus/medication/database/Medication.sql" />
<option value="file://$PROJECT_DIR$/src/main/resources/de/hitec/nhplus/medication/database/Medication_Ingredient.sql" />
</array> </array>
</option> </option>
<option name="outLayout" value="File per object by schema.groovy" /> <option name="outLayout" value="File per object by schema.groovy" />

View file

@ -3,7 +3,6 @@
<component name="SqlDialectMappings"> <component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/src/main/java/de/hitec/nhplus/patient/database/PatientDao.java" dialect="GenericSQL" /> <file url="file://$PROJECT_DIR$/src/main/java/de/hitec/nhplus/patient/database/PatientDao.java" dialect="GenericSQL" />
<file url="file://$PROJECT_DIR$/src/main/java/de/hitec/nhplus/treatment/database/TreatmentDao.java" dialect="GenericSQL" /> <file url="file://$PROJECT_DIR$/src/main/java/de/hitec/nhplus/treatment/database/TreatmentDao.java" dialect="GenericSQL" />
<file url="file://$PROJECT_DIR$/src/main/java/de/hitec/nhplus/treatment/database/NurseDao.java" dialect="GenericSQL" />
<file url="PROJECT" dialect="SQLite" /> <file url="PROJECT" dialect="SQLite" />
</component> </component>
</project> </project>

Binary file not shown.

View file

@ -1,5 +1,6 @@
package de.hitec.nhplus.datastorage; package de.hitec.nhplus.datastorage;
import de.hitec.nhplus.medication.database.MedicationDao;
import de.hitec.nhplus.nurse.database.NurseDao; import de.hitec.nhplus.nurse.database.NurseDao;
import de.hitec.nhplus.patient.database.PatientDao; import de.hitec.nhplus.patient.database.PatientDao;
import de.hitec.nhplus.treatment.database.TreatmentDao; import de.hitec.nhplus.treatment.database.TreatmentDao;
@ -56,4 +57,12 @@ public class DaoFactory {
public NurseDao createNurseDAO() { public NurseDao createNurseDAO() {
return new NurseDao(ConnectionBuilder.getConnection()); return new NurseDao(ConnectionBuilder.getConnection());
} }
/**
* @return a {@link MedicationDao}
* @author Dominik Säume
*/
public MedicationDao createMedicationDAO() {
return new MedicationDao(ConnectionBuilder.getConnection());
}
} }

View file

@ -20,7 +20,6 @@ public abstract class DaoImp<T> implements Dao<T> {
/** /**
* @param connection a Database Connection, which should be gotten from {@link ConnectionBuilder} * @param connection a Database Connection, which should be gotten from {@link ConnectionBuilder}
* @author Bernd Heidemann
*/ */
public DaoImp(Connection connection) { public DaoImp(Connection connection) {
this.connection = connection; this.connection = connection;
@ -30,7 +29,6 @@ public abstract class DaoImp<T> implements Dao<T> {
* Creates a new Database Entry from a Model object. * Creates a new Database Entry from a Model object.
* *
* @param t the Model instance * @param t the Model instance
* @author Bernd Heidemann
*/ */
@Override @Override
public void create(T t) throws SQLException { public void create(T t) throws SQLException {
@ -41,7 +39,6 @@ public abstract class DaoImp<T> implements Dao<T> {
* Read a Database Entry to a Model object. * Read a Database Entry to a Model object.
* *
* @param id of the Element in the Database * @param id of the Element in the Database
* @author Bernd Heidemann
*/ */
@Override @Override
public T read(int id) throws SQLException { public T read(int id) throws SQLException {
@ -55,8 +52,6 @@ public abstract class DaoImp<T> implements Dao<T> {
/** /**
* Read all Database Entries to a {@link List} of Model objects. * Read all Database Entries to a {@link List} of Model objects.
*
* @author Bernd Heidemann
*/ */
@Override @Override
public List<T> readAll() throws SQLException { public List<T> readAll() throws SQLException {
@ -67,7 +62,6 @@ public abstract class DaoImp<T> implements Dao<T> {
* Update the Database according to the Values of the Model object. * Update the Database according to the Values of the Model object.
* *
* @param t the Model instance. * @param t the Model instance.
* @author Bernd Heidemann
*/ */
@Override @Override
public void update(T t) throws SQLException { public void update(T t) throws SQLException {
@ -78,7 +72,6 @@ public abstract class DaoImp<T> implements Dao<T> {
* Delete a Database Entry. * Delete a Database Entry.
* *
* @param id of the Element in the Database. * @param id of the Element in the Database.
* @author Bernd Heidemann
*/ */
@Override @Override
public void delete(int id) throws SQLException { public void delete(int id) throws SQLException {

View file

@ -29,6 +29,11 @@ public class Fixtures
nurseFixture.setupTable(connection); nurseFixture.setupTable(connection);
nurseFixture.load(); nurseFixture.load();
MedicationFixture medicationFixture = new MedicationFixture();
medicationFixture.dropTable(connection);
medicationFixture.setupTable(connection);
medicationFixture.load();
} catch (Exception exception){ } catch (Exception exception){
System.out.println(exception.getMessage()); System.out.println(exception.getMessage());
} }

View file

@ -0,0 +1,157 @@
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.*;
public class MedicationFixture implements Fixture<Medication> {
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";
@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");
}
@Override
public void setupTable(Connection connection) throws SQLException {
final InputStream schema = Main.class.getResourceAsStream(SCHEMA);
final InputStream ingredientSchema = Main.class.getResourceAsStream(INGREDIENT_SCHEMA);
assert schema != null;
assert ingredientSchema != null;
String SQL = new Scanner(schema, StandardCharsets.UTF_8)
.useDelimiter("\\A")
.next();
String ingredientSQL = ";" + new Scanner(ingredientSchema, StandardCharsets.UTF_8)
.useDelimiter("\\A")
.next();
connection.createStatement().execute(SQL);
connection.createStatement().execute(ingredientSQL);
}
@Override
public Map<String, Medication> load() throws SQLException {
List<Medication> medications = new ArrayList<>();
Ingredient metforminhydrochlorid = new Ingredient("Metforminhydrochlorid");
Ingredient cellulose = new Ingredient("Cellulose");
Ingredient povidon = new Ingredient("Povidon");
Ingredient magnesiumstearat = new Ingredient("Magnesiumstearat");
Ingredient lisinoprilDihydrat = new Ingredient("Lisinopril-Dihydrat");
Ingredient mannitol = new Ingredient("Mannitol");
Ingredient calciumphosphat = new Ingredient("Calciumphosphat");
Ingredient simvastatin = new Ingredient("Simvastatin");
Ingredient laktose = new Ingredient("Laktose");
Ingredient enoxaparinNatrium = new Ingredient("Enoxaparin-Natrium");
Ingredient benzylalkohol = new Ingredient("Benzylalkohol");
Ingredient wasser = new Ingredient("Wasser");
Ingredient levothyroxinnatrium = new Ingredient("Levothyroxinnatrium");
Ingredient staerke = new Ingredient("Stärke");
Ingredient akaziengummi = new Ingredient("Akaziengummi");
Ingredient warfarinnatrium = new Ingredient("Warfarinnatrium");
medications.add(new Medication(
1,
"Metformin",
"AstraZeneca",
List.of(
metforminhydrochlorid,
cellulose,
povidon,
magnesiumstearat
),
"Übelkeit, Durchfall, Laktatazidose (selten)",
"Oral",
100
));
medications.add(new Medication(
2,
"Lisinopril",
"Teva Pharmaceuticals",
List.of(
lisinoprilDihydrat,
mannitol,
calciumphosphat,
magnesiumstearat
),
"Schwindel, trockener Husten",
"Oral",
150
));
medications.add(new Medication(
3,
"Simvastatin",
"Mylan",
List.of(
simvastatin,
laktose,
cellulose,
magnesiumstearat
),
"Muskelschmerzen, Leberprobleme(selten)",
"Oral",
80
));
medications.add(new Medication(
4,
"Enoxaparin",
"Sanofi",
List.of(
enoxaparinNatrium,
benzylalkohol,
wasser
),
"Blutungen, Reaktionen an der Injektionsstelle",
"Unterhautinjektion",
120
));
medications.add(new Medication(
5,
"Levothyroxin",
"Sandoz",
List.of(
levothyroxinnatrium,
laktose,
staerke,
akaziengummi
),
"Herzrasen, Gewichtsverlust",
"Oral",
90
));
medications.add(new Medication(
6,
"Warfarin",
"Apotex Inc.",
List.of(
warfarinnatrium,
laktose,
staerke,
magnesiumstearat
),
"Blutungen, Blutergüsse",
"Oral",
110
));
MedicationDao dao = DaoFactory.getInstance().createMedicationDAO();
Map<String, Medication> medicationsByName = new HashMap<>();
for (Medication medication : medications) {
dao.create(medication);
medicationsByName.put(medication.getName(), medication);
}
return medicationsByName;
}
}

View file

@ -14,7 +14,7 @@ import java.util.*;
public class NurseFixture implements Fixture<Nurse> { public class NurseFixture implements Fixture<Nurse> {
@Override @Override
public void dropTable(Connection connection) throws SQLException { public void dropTable(Connection connection) throws SQLException {
connection.createStatement().execute("DROP TABLE nurse"); connection.createStatement().execute("DROP TABLE IF EXISTS nurse");
} }
@Override @Override

View file

@ -16,7 +16,7 @@ import static de.hitec.nhplus.utils.DateConverter.convertStringToLocalDate;
public class PatientFixture implements Fixture<Patient> { public class PatientFixture implements Fixture<Patient> {
@Override @Override
public void dropTable(Connection connection) throws SQLException { public void dropTable(Connection connection) throws SQLException {
connection.createStatement().execute("DROP TABLE patient"); connection.createStatement().execute("DROP TABLE IF EXISTS patient");
} }
@Override @Override

View file

@ -24,7 +24,7 @@ public class TreatmentFixture implements Fixture<Treatment> {
@Override @Override
public void dropTable(Connection connection) throws SQLException { public void dropTable(Connection connection) throws SQLException {
connection.createStatement().execute("DROP TABLE treatment"); connection.createStatement().execute("DROP TABLE IF EXISTS treatment");
} }
@Override @Override

View file

@ -0,0 +1,25 @@
package de.hitec.nhplus.medication;
import javafx.beans.property.SimpleStringProperty;
public class Ingredient {
private final SimpleStringProperty name;
public Ingredient(String name) {
this.name = new SimpleStringProperty(name);
}
public String getName() {
return name.get();
}
public SimpleStringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
}

View file

@ -0,0 +1,152 @@
package de.hitec.nhplus.medication;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
public class Medication {
private SimpleIntegerProperty id;
private final SimpleStringProperty name;
private final SimpleStringProperty manufacturer;
private final SimpleListProperty<Ingredient> ingredients;
private final SimpleStringProperty possibleSideEffects;
private final SimpleStringProperty administrationMethod;
private final SimpleIntegerProperty currentStock;
public Medication(
String name,
String manufacturer,
List<Ingredient> ingredients,
String possibleSideEffects,
String administrationMethod,
int currentStock
) {
this.name = new SimpleStringProperty(name);
this.manufacturer = new SimpleStringProperty(manufacturer);
this.ingredients = new SimpleListProperty<>(FXCollections.observableArrayList(ingredients));
this.possibleSideEffects = new SimpleStringProperty(possibleSideEffects);
this.administrationMethod = new SimpleStringProperty(administrationMethod);
this.currentStock = new SimpleIntegerProperty(currentStock);
}
public Medication(
int id,
String name,
String manufacturer,
List<Ingredient> ingredients,
String possibleSideEffects,
String administrationMethod,
int currentStock
) {
this.id = new SimpleIntegerProperty(id);
this.name = new SimpleStringProperty(name);
this.manufacturer = new SimpleStringProperty(manufacturer);
this.ingredients = new SimpleListProperty<>(FXCollections.observableArrayList(ingredients));
this.possibleSideEffects = new SimpleStringProperty(possibleSideEffects);
this.administrationMethod = new SimpleStringProperty(administrationMethod);
this.currentStock = new SimpleIntegerProperty(currentStock);
}
public int getId() {
return id.get();
}
public SimpleIntegerProperty idProperty() {
return id;
}
public String getName() {
return name.get();
}
public SimpleStringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public String getManufacturer() {
return manufacturer.get();
}
public SimpleStringProperty manufacturerProperty() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer.set(manufacturer);
}
public ObservableList<Ingredient> getIngredients() {
return ingredients.get();
}
public SimpleListProperty<Ingredient> ingredientsProperty() {
return ingredients;
}
public void setIngredients(List<Ingredient> ingredients) {
this.ingredients.set(FXCollections.observableArrayList(ingredients));
}
public String getPossibleSideEffects() {
return possibleSideEffects.get();
}
public SimpleStringProperty possibleSideEffectsProperty() {
return possibleSideEffects;
}
public void setPossibleSideEffects(String possibleSideEffects) {
this.possibleSideEffects.set(possibleSideEffects);
}
public String getAdministrationMethod() {
return administrationMethod.get();
}
public SimpleStringProperty administrationMethodProperty() {
return administrationMethod;
}
public void setAdministrationMethod(String administrationMethod) {
this.administrationMethod.set(administrationMethod);
}
public int getCurrentStock() {
return currentStock.get();
}
public SimpleIntegerProperty currentStockProperty() {
return currentStock;
}
public void setCurrentStock(int currentStock) {
this.currentStock.set(currentStock);
}
@Override
public String toString() {
return new StringJoiner(System.lineSeparator())
.add("MEDICATION")
.add("ID: " + this.getId())
.add("Name: " + this.getName())
.add("Manufacturer: " + this.getManufacturer())
.add("Ingredients: " + this.getIngredients()
.stream()
.map(Ingredient::getName)
.collect(Collectors.joining(", ", "[", "]")))
.add("Possible Side Effects: " + this.getPossibleSideEffects())
.add("Administration Method: " + this.getAdministrationMethod())
.add("Current Stock: " + this.getCurrentStock())
.toString();
}
}

View file

@ -0,0 +1,161 @@
package de.hitec.nhplus.medication.database;
import de.hitec.nhplus.datastorage.Dao;
import de.hitec.nhplus.medication.Ingredient;
import de.hitec.nhplus.medication.Medication;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MedicationDao implements Dao<Medication> {
protected final Connection connection;
public MedicationDao(Connection connection) {
this.connection = connection;
}
@Override
public void create(Medication medication) throws SQLException {
final String medicationSQL = """
INSERT INTO medication
(name, manufacturer, possibleSideEffects, administrationMethod, currentStock)
VALUES (?, ?, ?, ?, ?);
""";
PreparedStatement medicationStatement = this.connection.prepareStatement(medicationSQL);
medicationStatement.setString(1, medication.getName());
medicationStatement.setString(2, medication.getManufacturer());
medicationStatement.setString(3, medication.getPossibleSideEffects());
medicationStatement.setString(4, medication.getAdministrationMethod());
medicationStatement.setInt(5, medication.getCurrentStock());
medicationStatement.execute();
final String ingredientSQL = """
INSERT INTO medication_ingredient
(id, name)
VALUES (?, ?);
""";
for (Ingredient ingredient : medication.getIngredients()) {
PreparedStatement ingredientStatement = this.connection.prepareStatement(ingredientSQL);
ingredientStatement.setInt(1, medication.getId());
ingredientStatement.setString(2, ingredient.getName());
ingredientStatement.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();
return getInstanceFromResultSet(result);
}
@Override
public List<Medication> readAll() throws SQLException {
final String SQL = """
SELECT medication.*, medication_ingredient.id
FROM medication LEFT JOIN
medication_ingredient ON medication.id = medication_ingredient.id
""";
ResultSet result = connection.prepareStatement(SQL).executeQuery();
Map<Integer, List<ResultSet>> resultSetMap = new HashMap<>();
while (result.next()) {
List<ResultSet> resultSetList = resultSetMap.computeIfAbsent(result.getInt(0), k -> new ArrayList<>());
resultSetList.add(result);
}
List<Medication> medications = new ArrayList<>();
for (Map.Entry<Integer, List<ResultSet>> entry : resultSetMap.entrySet()) {
medications.add(getInstanceFromResultSet(this.mergeResultSets(entry.getValue())));
}
return medications;
}
@Override
public void update(Medication medication) throws SQLException {
final String SQL = """
UPDATE medication SET
name = ?,
manufacturer = ?,
possibleSideEffects = ?,
administrationMethod = ?,
currentStock = ?
WHERE id = ?
""";
PreparedStatement preparedStatement = this.connection.prepareStatement(SQL);
preparedStatement.setString(1, medication.getName());
preparedStatement.setString(2, medication.getManufacturer());
preparedStatement.setString(3, medication.getPossibleSideEffects());
preparedStatement.setString(4, medication.getAdministrationMethod());
preparedStatement.setInt(5, medication.getCurrentStock());
preparedStatement.setInt(6, medication.getId());
preparedStatement.executeUpdate();
}
@Override
public void delete(int id) throws SQLException {
final String SQL = """
DELETE FROM medication WHERE medication.id = ?;
""";
PreparedStatement preparedStatement = this.connection.prepareStatement(SQL);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
}
private Medication getInstanceFromResultSet(ResultSet result) throws SQLException {
Medication medication = new Medication(
result.getInt(1),
result.getString(2),
result.getString(3),
null,
result.getString(4),
result.getString(5),
result.getInt(6)
);
List<Ingredient> ingredients = new ArrayList<>();
while (result.next()) {
ingredients.add(new Ingredient(result.getString(2)));
}
medication.setIngredients(ingredients);
return medication;
}
/**
* Merges a List of ResultSets to one for further use.
*
* @param resultSetList the {@link List} of {@link ResultSet} to merge
* @return merged {@link ResultSet}
*/
private ResultSet mergeResultSets(List<ResultSet> resultSetList) throws SQLException {
ResultSetMetaData metaData = resultSetList.get(0).getMetaData();
CachedRowSet cachedRowSet = RowSetProvider.newFactory().createCachedRowSet();
cachedRowSet.populate(resultSetList.get(0));
for (int i = 1; i < resultSetList.size(); i++) {
ResultSet resultSet = resultSetList.get(i);
while (resultSet.next()) {
cachedRowSet.moveToInsertRow();
for (int j = 1; j <= metaData.getColumnCount(); j++) {
cachedRowSet.updateObject(j, resultSet.getObject(j));
}
cachedRowSet.insertRow();
}
}
cachedRowSet.moveToCurrentRow();
return cachedRowSet;
}
}

View file

@ -0,0 +1,9 @@
CREATE TABLE medication
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
manufacturer TEXT NOT NULL,
possibleSideEffects TEXT NOT NULL,
administrationMethod TEXT NOT NULL,
currentStock INTEGER NOT NULL
)

View file

@ -0,0 +1,6 @@
CREATE TABLE medication_ingredient
(
id INTEGER NOT NULL ,
name TEXT NOT NULL,
FOREIGN KEY (id) REFERENCES medication (id) ON DELETE CASCADE
)