...

/

Solution: Fine Calculation System

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
@Document
public class Book {
@Id
private String id;
private String name;
private String summary;
private Boolean available;
@CreatedBy
private String createdBy;
@CreatedDate
private Date createdDate;
@LastModifiedBy
private String lastModifiedBy;
@LastModifiedDate
private Date lastModifiedDate;
@DBRef
private List<Author> authors;
@Override
public 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
@Document
public class BookLoanEntry {
@Id
private String id;
private String userFirstName;
private String userLastName;
@DBRef
private Book book;
private Date loanDate;
private Date dueDate;
private Date returnDate;
private String status;
@CreatedBy
private String createdBy;
@CreatedDate
private Date createdDate;
@LastModifiedBy
private String lastModifiedBy;
@LastModifiedDate
private Date lastModifiedDate;
}

Explanation:

  • Lines 10–12: We add annotations like @Data and @Document to transform a class into a document. ...