Contenido del Curso
Java Data Structures
Java Data Structures
CRUD operations
Basic Operations for a Database
In the previous chapter, you completed a fairly complex and interesting task on library management. You implemented methods for adding, retrieving, and removing elements from the list there. Did you know that such operations are essential for every list and application? These operations are referred to as CRUD operations!
CRUD stands for CREATE, READ, UPDATE, and DELETE, representing a list of operations to be performed on a database. In our case, in the previous task, the class Library
served as our database, specifically the list of books. We wrote fundamental operations for working with this list, slightly customizing each of them. We created more focused methods for retrieving a book by author or obtaining a list of books published after a specific year.
Similar operations are employed in large applications to interact with databases. In the end, our application should:
- Be able to create data in the database;
- Be able to read data from the database;
- Be able to update specific data in the database;
- Be able to delete data from the database.
Note
Note that in our case, the database is represented by a data structure, a list, which currently serves as our workaround. In the future, instead of a simple list, we will use a database.
You may have noticed we didn't implement the update method in the previous task.
Let's do that now:
We first need to retrieve the book by ID to update an element by ID. For this, we will implement a method that fetches the book by ID. It's better to do it this way than to implement the logic of getting a book by its ID in the book update method, as we can reuse this method in other functions, making it more versatile.
Library
public Book findBookById(int id) { Book result; for (Book book : books) { if (book.getId() == id){ result = book; } } return result; }
The solution above is a good option, but there is a small problem. We will get an error if such an ID does not exist in our list. We need to handle this error and display a message on the screen indicating that there is no such book in the list (database).
Library
public Book findBookById(int id) { Book result = null; for (Book book : books) { if (book.getId() == id){ result = book; } } if (result == null) { result = new Book("Unknown", "Unknown", 0); } return result; }
We initially initialize the variable result
as null in this solution. After implementing the book search by ID, we perform a check to see if our result is still null. If it's true
, we create a new undefined book.
Let's move on to implementing the update method:
Library
public void updateBookById(int id, Book newBook) { Book bookToBeUpdated = findBookById(id); for (Book book : books) { if (book.getId().equals(bookToBeUpdated.getId())) { book.setId(newBook.getId()); book.setAuthor(newBook.getAuthor()); book.setTitle(newBook.getTitle()); book.setYear(newBook.getYear()); return; // ending loop execution, because update operation has executed successfully } } }
Great! We updated the book by updating all its parameters. I highly recommend doing it this way because if we simply reassign the book, unexpected errors may occur. This way, we update the book by ID, reassigning it to the parameters of the new book. Now, let's use the update method and see what happens:
main
package com.example; import java.util.ArrayList; import java.util.List; class Main { public static void main(String[] args) { Library library = new Library(); library.addBook(new Book("Java: The Complete Reference", "Herbert Schildt", 2019)); library.addBook(new Book("Effective Java", "Joshua Bloch", 2020)); library.addBook(new Book("Clean Code", "Robert C. Martin", 2008)); System.out.println("All books in the library:"); library.displayAllBooks(); Book newBook = new Book("Head First Java", "Katy Siera", 2022); library.updateBookById(2, newBook); System.out.println("\nAll books after using update method"); library.displayAllBooks(); } } class Book { private static Long nextId = 1L; private String title; private String author; private int year; private Long id; public Book(String title, String author, int year) { this.title = title; this.author = author; this.year = year; this.id = nextId++; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public String toString() { return "Book{" + "title='" + title + '\'' + ", author='" + author + '\'' + ", year=" + year + ", id=" + id + '}'; } } class Library { public List<Book> books = new ArrayList<>(); public void addBook(Book book) { books.add(book); } public void removeBookById(int id) { List<Book> booksToRemove = new ArrayList<>(); for (Book book : books) { if (book.getId() == id) { booksToRemove.add(book); } } books.removeAll(booksToRemove); } public List<Book> findBooksByAuthor(String author) { List<Book> booksWithSpecifiedAuthor = new ArrayList<>(); for (Book book : books) { if (book.getAuthor().equals(author)) { booksWithSpecifiedAuthor.add(book); } } return booksWithSpecifiedAuthor; } public List<Book> findBooksPublishedAfterYear(int year) { List<Book> booksPublishedAfterYear = new ArrayList<>(); for (Book book : books) { if (book.getYear() > year){ booksPublishedAfterYear.add(book); } } return booksPublishedAfterYear; } public Book findBookById(int id) { Book result = null; for (Book book : books) { if (book.getId() == id){ result = book; } } if (result == null) { result = new Book("Unknown", "Unknown", 0); } return result; } public void updateBookById(int id, Book newBook) { Book bookToBeUpdated = findBookById(id); for (Book book : books) { if (book.getId().equals(bookToBeUpdated.getId())) { book.setId(newBook.getId()); book.setAuthor(newBook.getAuthor()); book.setTitle(newBook.getTitle()); book.setYear(newBook.getYear()); return; // ending loop execution, because update operation has executed successfully } } } public void displayAllBooks() { System.out.println(books); } }
Now, the Library
class has all CRUD operations.
You've done a great job if you grasped all of this. I recommend copying the methods I showed in this chapter and adding them to your code from the previous assignment, as this updated code will come in handy later.
¡Gracias por tus comentarios!