1
Controller class where the ID search method is found:
package br.com.apisw.controller;
import java.util.List;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import br.com.apisw.models.Planeta;
import br.com.apisw.repositories.PlanetaRepository;
@Controller
public class PlanetaController {
// Spring faz a injeção do repositório automaticamente
@Autowired
private PlanetaRepository repository;
@GetMapping("/planeta/cadastrar")
public String cadastrar(Model model) {
// cria o objeto planeta e envia pro html
model.addAttribute("planeta", new Planeta());
return "planeta/cadastrar";
}
@PostMapping("/planeta/salvar")
// recebendo o objeto planeta enviado do formulário
public String salvar(@ModelAttribute Planeta planeta) {
System.out.println(planeta);
repository.salvar(planeta);
return "redirect:/";
}
// metodo listar planetas
@GetMapping("/planeta/listar")
public String listar(Model model) {
List<Planeta> planeta = repository.obterTodosPlanetas();
model.addAttribute("planeta", planeta);
return "planeta/listar";
}
// metodo pesquisar por nome
@GetMapping("/planeta/pesquisarnome")
public String pesquisarNome() {
return "planeta/pesquisarnome";
}
// metodo pesquisar
@GetMapping("/planeta/pesquisar")
public String pesquisar(@RequestParam("nome") String nome, Model model) {
List<Planeta> planetas = repository.pesquisarPor(nome);
model.addAttribute("planeta", planetas);
return "planeta/pesquisarnome";
}
// metodo pesquisar por id
@GetMapping("/planeta/pesquisarid")
public String pesquisarId() {
return "planeta/pesquisarid";
}
// metodo pesquisar
@GetMapping("/planeta/pesquisaridplaneta")
public String pesquisarIdPlaneta(@RequestParam("id") String id, Model model) {
List<Planeta> planetas = repository.pesquisarPorId(id);
model.addAttribute("planeta", planetas);
return "planeta/pesquisarid";
}
}
Repositories class where the searchPorId method brings the collections of planets in the mongoDB database:
package br.com.apisw.repositories;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import org.bson.codecs.Codec;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.springframework.stereotype.Repository;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import br.com.apisw.codecs.PlanetaCodec;
import br.com.apisw.models.Planeta;
@Repository
public class PlanetaRepository {
private MongoClient cliente;
private MongoDatabase bancoDeDados;
// metodo que abre a conexão e persiste os dados
private void criarConexao() {
// captura o codec de Document
Codec<Document> codec = MongoClient.getDefaultCodecRegistry().get(Document.class);
// cria uma instância do PlanetaCodec
PlanetaCodec planetaCodec = new PlanetaCodec(codec);
// inclui em um registrador de codecs
CodecRegistry registro = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(),
CodecRegistries.fromCodecs(planetaCodec));
// cria um objeto do tipo MongoClientOptions que no momento da conexão com o
// Mongo, como opção, ele tenha todos os codecs necessários
MongoClientOptions opcoes = MongoClientOptions.builder().codecRegistry(registro).build();
// configuração das conexões com o MongoDB
this.cliente = new MongoClient("localhost:27017", opcoes);
this.bancoDeDados = cliente.getDatabase("apiSW");
}
// fecha a conexao com o MongoBD
private void fecharConexao() {
this.cliente.close();
}
// metodo salvar onde recebe o objeto planeta
public void salvar(Planeta planeta) {
criarConexao();
MongoCollection<Planeta> planetas = this.bancoDeDados.getCollection("planeta", Planeta.class);
planetas.insertOne(planeta);
fecharConexao();
}
// metodo listar
public List<Planeta> obterTodosPlanetas() {
criarConexao();
MongoCollection<Planeta> planetas = this.bancoDeDados.getCollection("planeta", Planeta.class);
MongoCursor<Planeta> resultados = planetas.find().iterator();
List<Planeta> planetasEncotrados = popularPlanetas(resultados);
fecharConexao();
return planetasEncotrados;
}
// metodo pesquisar por nome
public List<Planeta> pesquisarPor(String nome) {
criarConexao();
MongoCollection<Planeta> planetaCollection = this.bancoDeDados.getCollection("planeta", Planeta.class);
MongoCursor<Planeta> resultados = planetaCollection.find(Filters.eq("nome", nome), Planeta.class).iterator();
List<Planeta> planetas = popularPlanetas(resultados);
fecharConexao();
return planetas;
}
// metodo pesquisar por ID
public List<Planeta> pesquisarPorId(String id) {
criarConexao();
MongoCollection<Planeta> planetaCollection = this.bancoDeDados.getCollection("planeta", Planeta.class);
MongoCursor<Planeta> resultados = planetaCollection.find(Filters.eq("_id", id), Planeta.class).iterator();
List<Planeta> planetas = popularPlanetas(resultados);
fecharConexao();
return planetas;
}
// metodo que itera sobre os planetas no banco
private List<Planeta> popularPlanetas(MongoCursor<Planeta> resultados) {
List<Planeta> planetas = new ArrayList<>();
while (resultados.hasNext()) {
planetas.add(resultados.next());
}
return planetas;
}
}
User view in HTML and Thymeleaf:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<link type="text/css" rel="stylesheet"
href="../../materialize/css/materialize.min.css"
media="screen,projection" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet" />
<title>Sistema Star Wars</title>
<script type="text/javascript"
src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body class="grey lighten-3">
<div id="pesquisaPlaneta" class="container">
<h3 class="main-title center">Pesquisar Planeta</h3>
<form class="col s12" action="/planeta/pesquisaridplaneta" method="get">
<div class="row">
<div class="row">
<div class="input-field col s12">
<input id="id" name="id" type="text" /> <label
for="first_name">ID</label>
</div>
</div>
<div class="row">
<div class="input-field col s12 center">
<button class="btn waves-effect waves-light" type="submit">Pesquisar</button>
</div>
</div>
</div>
</form>
<div th:if="${planeta} != null">
<div class="row">
<div class="input-field col s12">
<table class="striped responsive-table">
<thead>
<tr>
<th style="text-align: center;">Nome</th>
<th style="text-align: center;">Clima</th>
<th style="text-align: center;">Terreno</th>
</tr>
</thead>
<tr th:each="planeta : ${planeta}">
<td style="text-align: center;" th:text="${planeta.nome}"></td>
<td style="text-align: center;" th:text="${planeta.clima}"></td>
<td style="text-align: center;" th:text="${planeta.terreno}"></td>
<td style="text-align: center;">
</tr>
</table>
</div>
</div>
</div>
</div>
<!-- Fim do formulario de pesquisa -->
<script type="text/javascript"
src="../../materialize/js/materialize.min.js"></script>
</body>
</html>
Example of the page search planets by ID where there is no return of the result:
It does not generate errors and when I debug the return is empty, I am not able to solve this problem, I need help!