diff --git a/db/mysql-with-inserts.sql b/db/mysql-with-inserts.sql index d7daea4bea4625b9b8785f6a0b9f9310cb870861..a77578cfea15728ddcb168525493d8146a7d28f1 100644 --- a/db/mysql-with-inserts.sql +++ b/db/mysql-with-inserts.sql @@ -15,6 +15,15 @@ CREATE TABLE `daaexample`.`users` ( PRIMARY KEY (`login`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE `daaexample`.`pets` ( + `id` int NOT NULL AUTO_INCREMENT, + `owner` int NOT NULL, + `name` varchar(50) NOT NULL, + `weight` float NOT NULL, + FOREIGN KEY (`owner`) REFERENCES people (`id`) ON DELETE CASCADE, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + CREATE USER IF NOT EXISTS 'daa'@'localhost' IDENTIFIED WITH mysql_native_password BY 'daa'; GRANT ALL ON `daaexample`.* TO 'daa'@'localhost'; @@ -27,6 +36,9 @@ INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'María','Nu INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Alba','Fernández'); INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Asunción','Jiménez'); +INSERT INTO `daaexample`.`pets` (`id`, `owner`, `name`,`weight`) VALUES (0,1,'Kirara',4.10); +INSERT INTO `daaexample`.`pets` (`id`, `owner`, `name`,`weight`) VALUES (0,3,'Yami',3.20); + -- The password for each user is its login suffixed with "pass". For example, user "admin" has the password "adminpass". INSERT INTO `daaexample`.`users` (`login`,`password`,`role`) VALUES ('admin', '713bfda78870bf9d1b261f565286f85e97ee614efe5f0faf7c34e7ca4f65baca','ADMIN'); diff --git a/db/mysql.sql b/db/mysql.sql index 116ae71b7273739848fe932b99815091eb683b79..fb454095d7e71162cabc1278d5598a4d789fd858 100644 --- a/db/mysql.sql +++ b/db/mysql.sql @@ -15,5 +15,14 @@ CREATE TABLE `daaexample`.`users` ( PRIMARY KEY (`login`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE `daaexample`.`pets` ( + `id` int NOT NULL AUTO_INCREMENT, + `owner` int NOT NULL, + `name` varchar(50) NOT NULL, + `weight` float NOT NULL, + FOREIGN KEY (`owner`) REFERENCES people (`id`) ON DELETE CASCADE, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + CREATE USER IF NOT EXISTS 'daa'@'localhost' IDENTIFIED WITH mysql_native_password BY 'daa'; GRANT ALL ON `daaexample`.* TO 'daa'@'localhost'; diff --git a/src/main/java/es/uvigo/esei/daa/dao/PetsDAO.java b/src/main/java/es/uvigo/esei/daa/dao/PetsDAO.java new file mode 100644 index 0000000000000000000000000000000000000000..619052b55f16d7739e731719e0eb9a0e0f4b4ac1 --- /dev/null +++ b/src/main/java/es/uvigo/esei/daa/dao/PetsDAO.java @@ -0,0 +1,234 @@ +package es.uvigo.esei.daa.dao; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.LinkedList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import es.uvigo.esei.daa.entities.Pet; + +public class PetsDAO extends DAO{ + private final static Logger LOG = Logger.getLogger(PeopleDAO.class.getName()); + + /** + * Returns a pet stored persisted in the system. + * + * @param id_owner identifier of the owner's animal. + * @param id_pet identifier of the id animal. + * @return a pet with the provided identifier. + * @throws DAOException if an error happens while retrieving the pet. + * @throws IllegalArgumentException if the provided id does not corresponds + * with any persisted pet. + */ + public Pet get(int id) + throws DAOException, IllegalArgumentException { + try (final Connection conn = this.getConnection()) { + final String query = "SELECT * FROM pets pt, people po WHERE pt.owner = po.id and pt.id=?"; + + try (final PreparedStatement statement = conn.prepareStatement(query)) { + statement.setInt(1, id); + + try (final ResultSet result = statement.executeQuery()) { + if (result.next()) { + return rowToEntity(result); + } else { + throw new IllegalArgumentException("Invalid id"); + } + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error getting a person", e); + throw new DAOException(e); + } + } + + + + + + + + /** + * Returns a list with all the people persisted in the system. + * + * @return a list with all the people persisted in the system. + * @throws DAOException if an error happens while retrieving the people. + */ + public List listWithOwner(int id) throws DAOException { + try (final Connection conn = this.getConnection()) { + final String query = "SELECT * FROM pets pt, people po WHERE pt.owner = po.id and po.id=?"; + + try (final PreparedStatement statement = conn.prepareStatement(query)) { + statement.setInt(1, id); + + try (final ResultSet result = statement.executeQuery()) { + final List pets = new LinkedList<>(); + + while (result.next()) { + pets.add(rowToEntity(result)); + } + + return pets; + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error listing pets with owner", e); + throw new DAOException(e); + } + } + + + + + + /** + * Returns a list with all the people persisted in the system. + * + * @return a list with all the people persisted in the system. + * @throws DAOException if an error happens while retrieving the people. + */ + public List list() throws DAOException { + try (final Connection conn = this.getConnection()) { + final String query = "SELECT * FROM pets"; + + try (final PreparedStatement statement = conn.prepareStatement(query)) { + try (final ResultSet result = statement.executeQuery()) { + final List pets = new LinkedList<>(); + + while (result.next()) { + pets.add(rowToEntity(result)); + } + + return pets; + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error listing pets", e); + throw new DAOException(e); + } + } + + + + /** + * Persists a new person in the system. An identifier will be assigned + * automatically to the new person. + * + * @param name name of the new person. Can't be {@code null}. + * @param surname surname of the new person. Can't be {@code null}. + * @return a {@link Person} entity representing the persisted person. + * @throws DAOException if an error happens while persisting the new person. + * @throws IllegalArgumentException if the name or surname are {@code null}. + */ + public Pet add(int owner, String name, float weight) + throws DAOException, IllegalArgumentException { + if (name == null) { + throw new IllegalArgumentException("name can't be null"); + } + + try (Connection conn = this.getConnection()) { + final String query = "INSERT INTO pets VALUES(null, ?, ?, ?)"; + + try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { + statement.setInt(1, owner); + statement.setString(2, name); + statement.setFloat(3, weight); + + if (statement.executeUpdate() == 1) { + try (ResultSet resultKeys = statement.getGeneratedKeys()) { + if (resultKeys.next()) { + return new Pet(resultKeys.getInt(1), owner, name, weight); + } else { + LOG.log(Level.SEVERE, "Error retrieving inserted id"); + throw new SQLException("Error retrieving inserted id"); + } + } + } else { + LOG.log(Level.SEVERE, "Error inserting value"); + throw new SQLException("Error inserting value"); + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error adding a pet", e); + throw new DAOException(e); + } + } + + /** + * Modifies a person previously persisted in the system. The person will be + * retrieved by the provided id and its current name and surname will be + * replaced with the provided. + * + * @param person a {@link Person} entity with the new data. + * @throws DAOException if an error happens while modifying the new person. + * @throws IllegalArgumentException if the person is {@code null}. + */ + public void modify(Pet pet) + throws DAOException, IllegalArgumentException { + if (pet == null) { + throw new IllegalArgumentException("pet can't be null"); + } + + try (Connection conn = this.getConnection()) { + final String query = "UPDATE pets SET owner=?, name=?, weight=? WHERE id=?"; + + try (PreparedStatement statement = conn.prepareStatement(query)) { + statement.setInt(1, pet.getOwner()); + statement.setString(2, pet.getName()); + statement.setFloat(3, pet.getWeight()); + statement.setInt(4, pet.getId()); + + if (statement.executeUpdate() != 1) { + throw new IllegalArgumentException("owner, name and weight can't be null"); + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error modifying a pet", e); + throw new DAOException(); + } + } + + /** + * Removes a persisted person from the system. + * + * @param id identifier of the person to be deleted. + * @throws DAOException if an error happens while deleting the person. + * @throws IllegalArgumentException if the provided id does not corresponds + * with any persisted person. + */ + public void delete(int id) + throws DAOException, IllegalArgumentException { + try (final Connection conn = this.getConnection()) { + final String query = "DELETE FROM pets WHERE id=?"; + + try (final PreparedStatement statement = conn.prepareStatement(query)) { + statement.setInt(1, id); + + if (statement.executeUpdate() != 1) { + throw new IllegalArgumentException("Invalid id"); + } + } + } catch (SQLException e) { + LOG.log(Level.SEVERE, "Error deleting a pet", e); + throw new DAOException(e); + } + } + + + private Pet rowToEntity(ResultSet row) throws SQLException { + return new Pet( + row.getInt("id"), + row.getInt("owner"), + row.getString("name"), + row.getFloat("weight") + ); + } + + +} + diff --git a/src/main/java/es/uvigo/esei/daa/entities/Pet.java b/src/main/java/es/uvigo/esei/daa/entities/Pet.java new file mode 100644 index 0000000000000000000000000000000000000000..9a6aa64b5f5d642c293b6e5d186373ca8f9223ef --- /dev/null +++ b/src/main/java/es/uvigo/esei/daa/entities/Pet.java @@ -0,0 +1,120 @@ +package es.uvigo.esei.daa.entities; + +import static java.util.Objects.requireNonNull; + +public class Pet { + private int id; + private int owner; + private String name; + private float weight; + + + // Constructor needed for the JSON conversion + Pet() {} + + + /** + * Constructs a new instance of {@link Pet}. + * + * @param id identifier of the pet. + * @param owner owner of the pet. + * @param name name of the pet. + * @param weight weight of the pet. + */ + public Pet(int id, int owner, String name, float weight) { + this.id = id; + this.owner = owner; + this.setName(name); + this.setWeight(weight); + } + + + /** + * Returns the identifier of the pet. + * + * @return the identifier of the pet. + */ + public int getId() { + return id; + } + + + /** + * Returns the owner of the pet. + * + * @return the owner of the pet. + */ + public int getOwner() { + return owner; + } + + + /** + * Returns the name of the pet. + * + * @return the name of the pet. + */ + public String getName() { + return name; + } + + + /** + * Set the name of this pet. + * + * @param name the new name of the pet. + * @throws NullPointerException if the {@code name} is {@code null}. + */ + public void setName(String name) { + this.name = requireNonNull(name, "Name can't be null"); + } + + + /** + * Returns the weight of the pet. + * + * @return the weight of the pet. + */ + public float getWeight() { + return weight; + } + + + /** + * Set the weight of this pet. + * + * @param weight the new weight of the pet. + * @throws NullPointerException if the {@code weight} is {@code null}. + */ + public void setWeight(float weight) { + this.weight = requireNonNull(weight, "Weight can't be null"); + } + + + @Override + public int hashCode() { + final int prime = 37; + int result = 1; + result = prime * result + id; + return result; + } + + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof Pet)) + return false; + Pet other = (Pet) obj; + if (id != other.id) + return false; + return true; + } + + + +} +