[JAVA] Create a simple search app with Spring Boot

As the title suggests, I created a search app.

usage environment

・ Windows10 (64bit) ・ Spring-boot: 2.2.6 -Eclipse: 4.9.0 ・ H2

Completion screen

When you enter any or all of the genre, author, title Pull the contents at the bottom of the screen. image.png

Entity

BookData.java


import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class BookData {

	@Id
	private long isbn;

	private String genre;
	private String author;
	private String title;
	private int stock;
	private Boolean status;

	public long getIsbn() {
		return isbn;
	}
	public void setIsbn(long isbn) {
		this.isbn = isbn;
	}
	public String getGenre() {
		return genre;
	}
	public void setGenre(String genre) {
		this.genre = genre;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public int getStock() {
		return stock;
	}
	public void setStock(int stock) {
		this.stock = stock;
	}
	public Boolean getStatus() {
		return status;
	}
	public void setStatus(Boolean status) {
		this.status = status;
	}
}

Dao Prepare a Dao class to search by genre, author, and title.

BookDataDao.java


import java.io.Serializable;
import java.util.List;

public interface BookDataDao extends Serializable {

	public List<BookData> search(String genre, String author, String title);
}

Repository Create a BookDataDaoImpl that implements the Dao class. Please refer to the comments for the contents of each description.

BookDataDaoImpl.java


import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class BookDataDaoImpl implements BookDataDao {

	//Providing the functions required to use Entity
	@Autowired
	private EntityManager entityManager;

	public BookDataDaoImpl() {
		super();
	}

	public BookDataDaoImpl(EntityManager manager) {
		this();
		entityManager = manager;
	}

	//Override the search method provided by Dao class
	@SuppressWarnings("unchecked")
	@Override
	public List<BookData> search(String genre, String author, String title) {

		//Concatenate SQL statements with StringBuilder
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT b From BookData b WHERE ");

		boolean genreFlg  = false;
		boolean authorFlg = false;
		boolean titleFlg  = false;
		boolean andFlg    = false;

		//Append to sql variable if genre is not blank
		//Set the flag to true
		if(!"".equals(genre)) {
			sql.append("b.genre LIKE :genre");
			genreFlg = true;
			andFlg   = true;
		}

		//append to sql variable if author is not blank
		//Set the flag to true
		if(!"".equals(author)) {
			if (andFlg) sql.append(" AND ");
			sql.append("b.author LIKE :author");
			authorFlg = true;
			andFlg    = true;
		}

		//Append to sql variable if title is not blank
		//Set the flag to true
		if(!"".equals(title)) {
			if (andFlg) sql.append(" AND ");
			sql.append("b.title LIKE :title");
			titleFlg = true;
			andFlg   = true;
		}

		/*
Query has a function equivalent to a query statement for querying data with SQL
Use entityManager's createQuery method
Pass sql variable as an argument
		*/
	    Query query = entityManager.createQuery(sql.toString());

	    //If the above if statement is true, set a value for each variable
	    //This time, I want to do an ambiguous search, so I use the like clause
	    if (genreFlg) query.setParameter("genre", "%" + genre + "%");
	    if (authorFlg) query.setParameter("author", "%" + author + "%");
	    if (titleFlg) query.setParameter("title", "%" + title + "%");
	    return query.getResultList();
	}
}

BookDataRepository

BookDataRepository.java


import org.springframework.data.jpa.repository.JpaRepository;

public interface BookDataRepository extends JpaRepository<BookData, Long> {

}

Service

BookService.java


import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BookService {

	@Autowired
	private BookDataRepository bookDataRepository;

	@Autowired
	private BookDataDaoImpl bookDataDaoImpl;


	//Search all
	public List<BookData> findAll(){
		return bookDataRepository.findAll();
	}

	//Find the corresponding ID
	public Optional<BookData> findById(long isbn) {
        return bookDataRepository.findById(isbn);
    }

	//Save
	public BookData save(BookData bookData) {
		return bookDataRepository.saveAndFlush(bookData);
	}

	//Search
	public List<BookData> search(String genre, String author, String title){

		List<BookData> result = new ArrayList<BookData>();

		//If all are blank, search all
		if ("".equals(genre) && "".equals(author) && "".equals(title)){
			result = bookDataRepository.findAll();
		}
		else {
			//Other than the above, call the method of BookDataDaoImpl
			result = bookDataDaoImpl.search(genre, author, title);
		}
		return result;
	}
}

Controller

StockController.java


import java.util.List;
import java.util.Optional;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/book")
public class StockController {

	@Autowired
	private BookService bookService;

	@PersistenceContext
	EntityManager entityManager;

	//List display processing
	@GetMapping
	public String index(Model model,@ModelAttribute("formModel") BookData bookdata) {

		model.addAttribute("msg", "Inventory control");
		model.addAttribute("msg2", "Please enter your search criteria");
		List<BookData> books = bookService.findAll();
		model.addAttribute("books", books);

		return "index";
	}

	//Search result receiving process
	//@Receive formModel from form with ModelAttribute
	//That type(BookData)And variables(bookdata)To specify
	@PostMapping
	public String select(@ModelAttribute("formModel") BookData bookdata, Model model) {

		model.addAttribute("msg", "search results");
		//Get each value with the getter of bookdata
		List<BookData> result = bookService.search(bookdata.getGenre(),bookdata.getAuthor(), bookdata.getTitle());
		model.addAttribute("books", result);

		return "index";
	}

	//Detailed screen processing
	//@Get the value received from the URL with PathVariable
	@GetMapping("detail/{isbn}")
	public String detail(@PathVariable long isbn, Model model) {

		model.addAttribute("msg", "Reference screen");
		Optional<BookData> data = bookService.findById(isbn);
		//When using Optional, the value is get()Get in
		model.addAttribute("form", data.get());

		return "detail";
	}


	//Initialization process
	@PostConstruct
	public void init() {

		BookData d1 = new BookData();
		d1.setAuthor("Natsume Soseki");
		d1.setTitle("Heart");
		d1.setGenre("literature");
		d1.setIsbn(11111);
		d1.setStock(100);
		d1.setStatus(false);
		bookService.save(d1);

		BookData d2 = new BookData();
		d2.setAuthor("Jiro Ohno");
		d2.setTitle("Introduction to Spring");
		d2.setGenre("Technology");
		d2.setIsbn(22222);
		d2.setStock(1);
		d2.setStatus(false);
		bookService.save(d2);

		BookData d3 = new BookData();
		d3.setAuthor("Taro Tanaka");
		d3.setTitle("How the network works");
		d3.setGenre("Technology");
		d3.setIsbn(33333);
		d3.setStock(20);
		d3.setStatus(false);
		bookService.save(d3);

		BookData d4 = new BookData();
		d4.setAuthor("Yoshikawa amount");
		d4.setTitle("Mud bullet");
		d4.setGenre("Mystery");
		d4.setIsbn(44444);
		d4.setStock(99);
		d4.setStatus(false);
		bookService.save(d4);

		BookData d5 = new BookData();
		d5.setAuthor("Natsume Soseki");
		d5.setTitle("Kusamakura");
		d5.setGenre("literature");
		d5.setIsbn(55555);
		d5.setStock(40);
		d5.setStatus(false);
		bookService.save(d5);

		BookData d6 = new BookData();
		d6.setAuthor("Test Toshiro");
		d6.setTitle("Serial murder case book");
		d6.setGenre("Mystery");
		d6.setIsbn(66666);
		d6.setStock(40);
		d6.setStatus(false);
		bookService.save(d6);

		BookData d7 = new BookData();
		d7.setAuthor("Taro Serpent");
		d7.setTitle("Getting Started with Java");
		d7.setGenre("Technology");
		d7.setIsbn(77777);
		d7.setStock(40);
		d7.setStatus(false);
		bookService.save(d7);
	}
}

index.html

index.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>initial screen</title>
<style>
h1 {font-size:18pt; font-weight:bold; color:gray;}
body {font-size:13pt; font-weight:bold; color:gray; margin:5px 25px;}
tr {margin:5px;}
th {padding:5px;color:white; background:darkgray;}
td {padding:5px;color:black; background:#f0f0f0;}
</style>
</head>
<body>
	<h1 th:text="${msg}"></h1>
		<p th:text="${msg2}"></p>
		<!--Enter the value th:object="${formModel}"Pack in-->
		<!--th:Make the initial value enter in value-->
		<form method="post" th:action="@{/book}" th:object="${formModel}">
			<label>Genre:</label>
			<input type="text" name="genre" th:value="*{genre}"><p>
			<label>Author:</label>
			<input type="text" name="author" th:value="*{author}"><p>
			<label>title:</label>
			<input type="text" name="title" th:value="*{title}"><p>
			<input type="submit" value="Search">
		</form>
		<table>
			<tr>
				<th>ISBN</th>
				<th>title</th>
				<th>Author name</th>
				<th>Stock quantity</th>
				<th>Genre</th>
			</tr>
			<tr th:each="obj:${books}" th:object="${obj}">
				<!--th:Link setting with href-->
				<td><a th:href="@{/book/detail/{isbn}(isbn=*{isbn})}" th:text="*{isbn}"></a></td>
				<td th:text="*{title}"></td>
				<td th:text="*{author}"></td>
				<td th:text="*{stock}"></td>
				<td th:text="*{genre}"></td>
			</tr>
		</table>
</body>
</html>

Processing pattern 1

Enter "literature" in the genre and press the search button. When you move to the search result screen, the value entered on the previous page is retained and displayed on the screen. Click the ISBN link in the search results to move to the reference screen. image.png

image.png

image.png

Processing pattern 2

Enter "thick" for the author and press the search button. image.png

image.png

Finally

I created a simple app. We would appreciate it if you could let us know if you have any opinions such as "It is better to do this!"

reference

[Introduction to Spring Boot 2 Programming](https://www.amazon.co.jp/Spring-Boot-2-%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9 % E3% 83% 9F% E3% 83% B3% E3% 82% B0% E5% 85% A5% E9% 96% 80-% E6% 8E% 8C% E7% 94% B0% E6% B4% A5% E8% 80% B6% E4% B9% 83-ebook / dp / B07KF4R1HT / ref = sr_1_3? __ mk_ja_JP =% E3% 82% AB% E3% 82% BF% E3% 82% AB% E3% 83% 8A & dchild = 1 & keywords = Spring + boot & qid = 1590664580 & sr = 8-3)

[Introduction to Spring](https://www.amazon.co.jp/Spring%E5%BE%B9%E5%BA%95%E5%85%A5%E9%96%80-Spring-Framework%E3% 81% AB% E3% 82% 88% E3% 82% 8BJava% E3% 82% A2% E3% 83% 97% E3% 83% AA% E3% 82% B1% E3% 83% BC% E3% 82% B7% E3% 83% A7% E3% 83% B3% E9% 96% 8B% E7% 99% BA-% E6% A0% AA% E5% BC% 8F% E4% BC% 9A% E7% A4% BENTT % E3% 83% 87% E3% 83% BC% E3% 82% BF-ebook / dp / B01IEWNLBU / ref = sr_1_2? __mk_ja_JP =% E3% 82% AB% E3% 82% BF% E3% 82% AB% E3% 83% 8A & dchild = 1 & keywords = Spring + boot & qid = 1590664580 & sr = 8-2)

Recommended Posts

Create a simple search app with Spring Boot
Create an app with Spring Boot 2
Create an app with Spring Boot
Create a simple demo site with Spring Security with Spring Boot 2.1
Create a simple on-demand batch with Spring Batch
I made a simple search form with Spring Boot + GitHub Search API.
Create a website with Spring Boot + Gradle (jdk1.8.x)
Create a web api server with spring boot
Create a Spring Boot development environment with docker
Create microservices with Spring Boot
Create a Spring Boot app development project with the cURL + tar command
Steps to create a simple camel app using Apache Camel Spring Boot starters
Create a portfolio app using Java and Spring Boot
Implement a simple Rest API with Spring Security with Spring Boot 2.0
Create Restapi with Spring Boot ((1) Until Run of App)
Create a Hello World web app with Spring framework + Jetty
Let's make a simple API with EC2 + RDS + Spring boot ①
Implement a simple Rest API with Spring Security & JWT with Spring Boot 2.0
[Rails6] Create a new app with Rails [Beginner]
Create a simple web application with Dropwizard
[Rails withdrawal] Create a simple withdrawal function with rails
Create a simple bar chart with MPAndroidChart
[Rails 5] Create a new app with Rails [Beginner]
Create a restaurant search app with IBM Watson + Gurunavi API (with source)
Create a simple bulletin board with Java + MySQL
Create a Spring Boot application using IntelliJ IDEA
Create CRUD apps with Spring Boot 2 + Thymeleaf + MyBatis
Create your own Utility with Thymeleaf with Spring Boot
Create Spring Boot environment with Windows + VS Code
Download with Spring Boot
Create Spring Cloud Config Server with security with Spring Boot 2.0
Create a docker image that runs a simple Java app
A simple CRUD app made with Nuxt / Laravel (Docker)
Practice making a simple chat app with Docker + Sinatra
[JUnit 5 compatible] Write a test using JUnit 5 with Spring boot 2.2, 2.3
How to create a Spring Boot project in IntelliJ
[Spring Boot] How to create a project (for beginners)
Create a Chat app with WebSocket (Tyrus) + libGDX + Kotlin
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
A memorandum when creating a REST service with Spring Boot
I wrote a test with Spring Boot + JUnit 5 now
Hello World (console app) with Apache Camel + Spring Boot 2
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Create a playground with Xcode 12
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Send email with spring boot
Create a web app that is just right for learning [Spring Boot + Thymeleaf + PostgreSQL]
[Rails] I tried to create a mini app with FullCalendar