Commit caf1c466 authored by DavidSholito's avatar DavidSholito

añadido clase Pet y DAO correspondiente

parent 845885fc
......@@ -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');
......
......@@ -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';
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<Pet> 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<Pet> 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<Pet> 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<Pet> 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")
);
}
}
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;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment