Solution: Fine Calculation System
Here's the solution to the fine calculation system challenge.
Solution
Let’s discuss the solution for implementing a fine calculation system.
Update the Book
document
First, we add the Boolean
available
property to the Book
class.
Press + to interact
package com.smartdiscover.document;import lombok.Data;import org.springframework.data.annotation.*;import org.springframework.data.mongodb.core.mapping.DBRef;import org.springframework.data.mongodb.core.mapping.Document;import java.util.Date;import java.util.List;import java.util.stream.Collectors;@Data@Documentpublic class Book {@Idprivate String id;private String name;private String summary;private Boolean available;@CreatedByprivate String createdBy;@CreatedDateprivate Date createdDate;@LastModifiedByprivate String lastModifiedBy;@LastModifiedDateprivate Date lastModifiedDate;@DBRefprivate List<Author> authors;@Overridepublic String toString() {return "Book{" +"id=" + id +", name='" + name + '\'' +", summary='" + summary + '\'' +((null != authors) ? ", authors=" + authors.stream().map(i -> i.getFirstName()).collect(Collectors.toList()) + '\'' : "") +", createdBy='" + createdBy + '\'' +", createdDate='" + createdDate + '\'' +", lastModifiedBy='" + lastModifiedBy + '\'' +", lastModifiedDate='" + lastModifiedDate + '\'' +'}';}}
Update the BookRepository
Then, we add the findByNameAndAvailableIsNullOrAvailableIsTrue
method in the BookRepository
interface to search for a book by matching the name and its availability as Null
or True
.
Press + to interact
package com.smartdiscover.repository;import com.smartdiscover.document.Book;import org.springframework.data.mongodb.repository.MongoRepository;import java.util.List;public interface BookRepository extends MongoRepository<Book, String> {Book findFirstByName(String name);List<Book> findAllByName(String name);Book findByNameAndAvailableIsNullOrAvailableIsTrue(String name);}
Create the BookLoanEntry
document
Then, we create the BookLoanEntry
class in the com.smartdiscover.document
package.
Press + to interact
package com.smartdiscover.document;import lombok.Data;import org.springframework.data.annotation.*;import org.springframework.data.mongodb.core.mapping.DBRef;import org.springframework.data.mongodb.core.mapping.Document;import java.util.Date;@Data@Documentpublic class BookLoanEntry {@Idprivate String id;private String userFirstName;private String userLastName;@DBRefprivate Book book;private Date loanDate;private Date dueDate;private Date returnDate;private String status;@CreatedByprivate String createdBy;@CreatedDateprivate Date createdDate;@LastModifiedByprivate String lastModifiedBy;@LastModifiedDateprivate Date lastModifiedDate;}
Explanation:
-
Lines 10–12: We add annotations like
@Data
and@Document
to transform a class into a document. ...