Can't connect Spring boot with MongoDb - java

I'm trying to make a simple progam with Spring Boot work with MongoDB in Spring Boot 2.3.9
From the startup logs I suspect that something is wrong, it seems like it's initialized twice.
This is my console output:
2021-03-08 01:54:43.515 INFO 26609 --- [ restartedMain] c.a.a.r.SpringbootRegistroApplication : Starting SpringbootRegistroApplication on santiagoVB with PID 26609 (/home/santiago/Documentos/workspace/springboot-registro/target/classes started by santiago in /home/santiago/Documentos/workspace/springboot-registro)
2021-03-08 01:54:43.521 INFO 26609 --- [ restartedMain] c.a.a.r.SpringbootRegistroApplication : No active profile set, falling back to default profiles: default
2021-03-08 01:54:43.680 INFO 26609 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-03-08 01:54:43.682 INFO 26609 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-03-08 01:54:45.719 INFO 26609 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-03-08 01:54:45.895 INFO 26609 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 167ms. Found 1 MongoDB repository interfaces.
2021-03-08 01:54:46.683 INFO 26609 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-03-08 01:54:46.699 INFO 26609 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-03-08 01:54:46.701 INFO 26609 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.43]
2021-03-08 01:54:46.830 INFO 26609 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-03-08 01:54:46.830 INFO 26609 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3147 ms
2021-03-08 01:54:47.152 INFO 26609 --- [ restartedMain] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2021-03-08 01:54:47.363 INFO 26609 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:12}] to localhost:27017
2021-03-08 01:54:47.372 INFO 26609 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=9, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=5581801}
2021-03-08 01:54:47.714 INFO 26609 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-03-08 01:54:48.326 INFO 26609 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-03-08 01:54:48.685 INFO 26609 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-03-08 01:54:48.701 INFO 26609 --- [ restartedMain] c.a.a.r.SpringbootRegistroApplication : Started SpringbootRegistroApplication in 6.21 seconds (JVM running for 9.239)
My pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.appcity.app.registro</groupId>
<artifactId>springboot-registro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-registro</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>15</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My application.properties:
spring.data.mongodb.uri=mongodb://localhost:27017/App
spring.data.mongodb.auto-index-creation=true
#spring.data.mongodb.host=localhost
#spring.data.mongodb.port=27017
#spring.data.mongodb.username=Udea
#spring.data.mongodb.password=udeapp
#spring.data.mongodb.database=App
My Object:
package com.appcity.app.registro.models.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "UsuarioDb")
public class UsuarioDb {
#Id
private String id;
private String username;
private String phone;
private String email;
private String password;
public UsuarioDb() {
super();
}
public UsuarioDb(String id, String username, String phone, String email, String password) {
super();
this.id = id;
this.username = username;
this.phone = phone;
this.email = email;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "UsuarioDb [id=" + id + ", username=" + username + ", phone=" + phone + ", email=" + email
+ ", password=" + password + "]";
}
}
My Interface:
package com.appcity.app.registro.models.dao;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.appcity.app.registro.models.entity.UsuarioDb;
#Repository
public interface RegistroDao extends MongoRepository<UsuarioDb, String>{
}
My Controller:
package com.appcity.app.registro.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.appcity.app.registro.models.dao.RegistroDao;
import com.appcity.app.registro.models.entity.UsuarioDb;
//#CrossOrigin
#RestController
public class RegistroController {
#Autowired
private RegistroDao repository;
#PostMapping("/registro/crear")
public String saveUsuarioDb(#RequestBody UsuarioDb usuarioDb) {
repository.save(usuarioDb);
return "Added usuarioDb with id : " + usuarioDb.getId();
}
#GetMapping("/registro/listar")
public List<UsuarioDb> getUsers(){
return repository.findAll();
}
#GetMapping("/registro/listar/{id}")
public Optional<UsuarioDb> getUser(#PathVariable String id){
return repository.findById(id);
}
#DeleteMapping("/registro/eliminar/{id}")
public String deleteUser(#PathVariable String id) {
repository.deleteById(id);
return "usuarioDb deleted with id : "+id;
}
}
My MongoDb Status in Ubuntu:
● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2021-03-08 00:30:58 -05; 1h 46min ago
Docs: https://docs.mongodb.org/manual
Main PID: 21445 (mongod)
Memory: 160.1M
CGroup: /system.slice/mongod.service
└─21445 /usr/bin/mongod --config /etc/mongod.conf
mar 08 00:30:58 santiagoVB systemd[1]: Started MongoDB Database Server.
My database in MongoDb:
show dbs
App 0.000GB
admin 0.000GB
config 0.000GB
local 0.000GB
What am I doing wrong?
What configuration do I have wrong?

I ran into a similar kind of issue and I installed a different JDK patch. I had JDK 11.0.2 and I changed it to JDK 11.0.10 and It worked for me.
Also, you need to have the #CrossOrigin(origins = "*") annotation. * (asterisk) means you are allowing requests from any origin.

Related

Whitelabel error when i try make to make a get from database

I am trying to make a small rest-api in springboot but i always get this errorerror 404
It is connected to a database but when I try to exceute a GET from Post I also have 404 error
This is my structure
project structure
My pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>Clientix</groupId>
<artifactId>Ruben_DeNicolas</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Clientix</name>
<description>TFG</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Repository
package repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import models.ClientesModel;
#Repository
public interface ClientesRepository extends CrudRepository<ClientesModel, Integer>{
}
Service
package services;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import models.ClientesModel;
import repositories.ClientesRepository;
#Service
public class ClientesService {
#Autowired
ClientesRepository clientesRepository;
public ArrayList<ClientesModel>getClientes()
{
return(ArrayList<ClientesModel>)clientesRepository.findAll();
}
public ClientesModel insert(ClientesModel c)
{
return clientesRepository.save(c);
}
}
Model
package models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "clientes")
public class ClientesModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(unique = true, nullable = false)
private Integer idCliente;
private String NombreCliente;
private String CIFNIF;
private String DireccionFacturacion;
public ClientesModel(String NombreCliente) {
this.NombreCliente = NombreCliente;
}
public ClientesModel(int idCliente, String NombreCliente, String CIFNIF, String DireccionFacturacion) {
this.idCliente = idCliente;
this.NombreCliente = NombreCliente;
this.CIFNIF = CIFNIF;
this.DireccionFacturacion = DireccionFacturacion;
}
public Integer getIdCliente() {
return idCliente;
}
public void setIdCliente(Integer idCliente) {
this.idCliente = idCliente;
}
public String getNombreCliente() {
return NombreCliente;
}
public void setNombreCliente(String nombreCliente) {
NombreCliente = nombreCliente;
}
public String getCIFNIF() {
return CIFNIF;
}
public void setCIFNIF(String cIFNIF) {
CIFNIF = cIFNIF;
}
public String getDireccionFacturacion() {
return DireccionFacturacion;
}
public void setDireccionFacturacion(String direccionFacturacion) {
DireccionFacturacion = direccionFacturacion;
}
}
Controller
package controllers;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import models.ClientesModel;
import services.ClientesService;
#RestController
#RequestMapping(value = "/clientes",produces="application/json")
public class ClientesController {
#Autowired
ClientesService clientesService;
//OBTENER TODOS LOS CLIENTES
//#RequestMapping(value = "/",method = RequestMethod.GET)
#GetMapping()
public ArrayList<ClientesModel> getClientes()
{
return clientesService.getClientes();
}
//INSTERTAR CLIENTE
#PostMapping
public ClientesModel insert(#RequestBody ClientesModel c)
{
return this.clientesService.insert(c);
}
}
```
Clientix application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan()
public class ClientixApplication {
public static void main(String[] args) {
SpringApplication.run(ClientixApplication.class, args);
}
}
This is the SpringBoot log
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.6)
2022-04-06 16:05:32.098 INFO 15728 --- [ main] C.Ruben_DeNicolas.ClientixApplication : Starting ClientixApplication using Java 17.0.2 on DESKTOP-0EJNGE1 with PID 15728 (C:\Users\Rubén\Desktop\TestSpringBoot\Ruben_DeNicolas (1)\Ruben_DeNicolas\target\classes started by Rubén in C:\Users\Rubén\Desktop\TestSpringBoot\Ruben_DeNicolas (1)\Ruben_DeNicolas)
2022-04-06 16:05:32.101 INFO 15728 --- [ main] C.Ruben_DeNicolas.ClientixApplication : No active profile set, falling back to 1 default profile: "default"
2022-04-06 16:05:32.373 INFO 15728 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-04-06 16:05:32.381 INFO 15728 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 2 ms. Found 0 JPA repository interfaces.
2022-04-06 16:05:32.627 INFO 15728 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-04-06 16:05:32.632 INFO 15728 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-04-06 16:05:32.632 INFO 15728 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.60]
2022-04-06 16:05:32.692 INFO 15728 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-04-06 16:05:32.692 INFO 15728 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 569 ms
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2022-04-06 16:05:32.784 INFO 15728 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-04-06 16:05:32.810 INFO 15728 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.7.Final
2022-04-06 16:05:32.893 INFO 15728 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-04-06 16:05:32.945 INFO 15728 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-04-06 16:05:32.948 WARN 15728 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2022-04-06 16:05:33.018 INFO 15728 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-04-06 16:05:33.034 INFO 15728 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL55Dialect
2022-04-06 16:05:33.132 INFO 15728 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-04-06 16:05:33.138 INFO 15728 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-04-06 16:05:33.156 WARN 15728 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-04-06 16:05:33.313 INFO 15728 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-04-06 16:05:33.319 INFO 15728 --- [ main] C.Ruben_DeNicolas.ClientixApplication : Started ClientixApplication in 1.398 seconds (JVM running for 1.705)
2022-04-06 16:05:36.286 INFO 15728 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-04-06 16:05:36.287 INFO 15728 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-04-06 16:05:36.287 INFO 15728 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
what is the url your hitting on your browser, make sure not hitting with https...
Code looks okay, try hitting
http://localhost:8080/clientes

No mapping for GET /WEB-INF/pages/patients.jsp

I'm currently developing crud web-application with spingboot and hibernate, and experiencing difficulties with displaying pages in browser (returns "page not found" 404 error and no mapping warning in Spring log). For some reason I also cannot preview jsp-pages as Idea states that "There is no configured/running web-servers found!" even tough spring-web has embedded Tomcat server.
Webconfig:
package testgroup.private_clinic.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages ="testgroup.private_clinic")
public class Webconfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/res/**").addResourceLocations("/res/");
}
#Bean
ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setSuffix(".jsp");
viewResolver.setPrefix("/WEB-INF/pages/");
return viewResolver;
}
}
AppInitializer:
package testgroup.private_clinic.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{HibernateConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{Webconfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[] {characterEncodingFilter};
}
}
Controller:
package testgroup.private_clinic.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import testgroup.private_clinic.model.Patient;
import testgroup.private_clinic.service.PatientService;
import java.util.List;
#Controller
public class PatientController {
PatientService patientService;
#Autowired
public void setPatienceService(PatientService patientService){
this.patientService = patientService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView allPatients(){
List<Patient> patients = patientService.allPatients();
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("patients");
modelAndView.addObject("patientList", patients);
return modelAndView;
}
#RequestMapping(value= "/edit{id}", method = RequestMethod.GET)
public ModelAndView editPage(#PathVariable("id") int id){
Patient patient = patientService.getByID(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("editPage");
modelAndView.addObject("patient", patient);
return modelAndView;
}
#RequestMapping(value="/edit", method = RequestMethod.POST)
public ModelAndView editPatient(#ModelAttribute("patient") Patient patient){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("redirect:/");
patientService.edit(patient);
return modelAndView;
}
}
Pom-file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>testorg</groupId>
<artifactId>private_clinic</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.28.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
Spring log:
2021-03-06 02:46:33.941 INFO 13956 --- [ main] t.private_clinic.SpringBootClass : Starting SpringBootClass on DESKTOP-96Q7T8E with PID 13956 (C:\Users\Anton\IdeaProjects\Private_clinic_temp\target\classes started by Anton in C:\Users\Anton\IdeaProjects\Private_clinic_temp)
2021-03-06 02:46:33.943 INFO 13956 --- [ main] t.private_clinic.SpringBootClass : No active profile set, falling back to default profiles: default
2021-03-06 02:46:34.712 INFO 13956 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-03-06 02:46:34.719 INFO 13956 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-03-06 02:46:34.719 INFO 13956 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.43]
2021-03-06 02:46:34.793 INFO 13956 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-03-06 02:46:34.793 INFO 13956 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 820 ms
2021-03-06 02:46:34.900 INFO 13956 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.28.Final
2021-03-06 02:46:34.995 INFO 13956 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-03-06 02:46:35.107 INFO 13956 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
2021-03-06 02:46:35.506 INFO 13956 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-03-06 02:46:35.748 INFO 13956 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-03-06 02:46:35.756 INFO 13956 --- [ main] t.private_clinic.SpringBootClass : Started SpringBootClass in 2.044 seconds (JVM running for 2.527)
2021-03-06 02:46:48.864 INFO 13956 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-03-06 02:46:48.864 INFO 13956 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-03-06 02:46:48.868 INFO 13956 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
Hibernate: select patient0_.id as id1_0_0_, patient0_.adress as adress2_0_0_, patient0_.diagnosis as diagnosi3_0_0_, patient0_.patient_name as patient_4_0_0_, patient0_.patient_patronimic as patient_5_0_0_, patient0_.status as status6_0_0_, patient0_.patient_surname as patient_7_0_0_ from patients patient0_ where patient0_.id=?
2021-03-06 02:46:48.991 WARN 13956 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound : No mapping for GET /WEB-INF/pages/editPage.jsp
Main Class:
package testgroup.private_clinic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication(exclude = HibernateJpaAutoConfiguration.class)
public class SpringBootClass extends SpringBootServletInitializer {
public static void main(String[] args){
SpringApplication.run(SpringBootClass.class, args);
}
}

Thymeleaf won't recognize variable in HomeController and Java error in creating bean "homeController"

I've been debugging this web app for 2 hours now and I can't figure this out.
After placing the version variable in the application, removing the temp H2 DB and the data.sql file, then adding the driver to the pom.xml file to use the Postgres DB, it stopped working.
I attached all the necessary files but if you need something please comment.
In the application.properties I gave the variable version then used that in the HomeController (line 24) and the corresponding console error says, "could not resolve placeholder 'version'."
In the browser usually, there are error messages that I can dig through, but this time the browser on the localhost simply fails to load, This site can’t be reached, localhost refused to connect.
There are only two "Caused by" errors in the console logs below so I'm sure it is not that difficult to point out the bug.
After lots of research on StackOverflow, looking at other questions, and trial and error, I have run out of possible solutions to try that are applicable to my case. Would really appreciate it if someone would take a look at the attached code and let me know about any solutions. Any help is appreciated! Thank you very much in advance and I will check back.
Here's the file structure if that helps at all
Here's the 2nd part:
The spring.datasource.username=postgres is underlined in yellow in eclipse as well as the version=3.0.0 at the bottom, when I hover over the yellow line it says, "unknown property" on both.
Here is my application.properties file and the screenshot:
spring.datasource.url=jdbc:postgresql://localhost:5432/pma-database
spring.datasource.username=postgres
spring.datasource.password=password321
spring.datasource.initialization-mode=never
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.show-sql=true
spring.thymeleaf.cache=false
version=3.0.0
Here's the HomeController.java you'll see the #Value("${version}") is here on line 24 or so and the model.addAttribute("versionNumber", ver) is on line 36.
package com.project1.controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project1.dao.EmployeeRepository;
import com.project1.dao.ProjectRepository;
import com.project1.dto.ChartData;
import com.project1.dto.EmployeeProject;
import com.project1.entities.Project;
#Controller
public class HomeController {
#Value("${version}")
private String ver;
#Autowired
ProjectRepository proRepo;
#Autowired
EmployeeRepository empRepo;
#GetMapping("/")
public String displayHome(Model model) throws JsonProcessingException {
model.addAttribute("versionNumber", ver);
Map<String, Object> map = new HashMap<>();
//we are querying the DB for projects
List<Project> projects = proRepo.findAll();
model.addAttribute("projectsList", projects);
List<ChartData> projectData = proRepo.getProjectStatus();
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(projectData);
//[ ["NOTSTARTED, 1], ["INPROGRESS", 2], ["COMPLETED", 1] ]
model.addAttribute("projectStatusCnt", jsonString);
//we are querying the DB for employees
List<EmployeeProject> employeesProjectCnt = empRepo.employeeProjects();
model.addAttribute("employeesListProjectsCnt", employeesProjectCnt);
return "main/home";
}
}
Here's the home.html file which has the versionNumber variable in the tag, which is related to the issue at hand.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!-- this is the code for the header-->
<head th:replace="layouts::header"></head>
<!-- this is the code for the navbar-->
<nav th:replace="layouts::navbar"></nav>
<body>
<div class="container">
<h3>Main Dashboard</h3>
<a th:text="${versionNumber}"></a>
<hr>
<h4> Current Projects </h4>
<div class="row">
<div class="col-md-6">
<table class="table table-bordered table-striped">
<thead class="thead-dark">
<tr>
<th> Project Name </th>
<th> Project Stage </th>
</tr>
</thead>
<tbody>
<tr th:each="aProject : ${projectsList}">
<td th:text="${aProject.name}"></td>
<td th:text="${aProject.stage}"></td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-4">
<canvas id="myPieChart" height="50" width="50"></canvas>
<script>
var chartData = "[[${projectStatusCnt}]]"
</script>
</div>
</div>
</div>
<div class="container">
<h4> Current Employees </h4>
<div class="row">
<div class="col-md-6">
<table class="table table-bordered table-striped">
<thead class="thead-dark">
<tr>
<th> First Name </th>
<th> Last Name </th>
<th> Project Count</th>
</tr>
</thead>
<tbody>
<tr th:each="aEmployeeProjectCnt : ${employeesListProjectsCnt}">
<td th:text="${aEmployeeProjectCnt.firstName}"></td>
<td th:text="${aEmployeeProjectCnt.lastName}"></td>
<td th:text="${aEmployeeProjectCnt.projectCount}"></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript" th:src="#{js/myChart.js}"></script>
</body>
</html>
Here's the Employee class which has the GenerationStrategy. I tried
both GenerationTypes listed but they give the same exact error in the console logs.
#Id annotation
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="employee_seq")
Again the code snippet below was also tried but that gave me the same exact error as the code that I have attached below and these were recommendations from stackoverflow, but the application still won't work.
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="employee_seq")
#SequenceGenerator(allocationSize=1, name = "employee_generator")
Here's the Employee class
package com.project1.entities;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
#Entity
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="employee_seq")
#SequenceGenerator(allocationSize=1, name = "employee_generator")
private long employeeId;
private String firstName;
private String lastName;
private String email;
#ManyToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST},
fetch = FetchType.LAZY)
#JoinTable(name="project_employee",
joinColumns=#JoinColumn(name="employee_id"),
inverseJoinColumns=#JoinColumn(name="project_id")
)
private List<Project> projects;
public Employee() {
}
public Employee(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(long employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Also the same thing with the Project class
package com.project1.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
#Entity
public class Project {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="project_seq")
#SequenceGenerator(allocationSize=1, name = "project_generator")
private long projectId;
private String name;
private String stage; // NOTSTARTED, COMPLETED, INPROGRESS
private String description;
#ManyToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST},
fetch = FetchType.LAZY)
#JoinTable(name="project_employee",
joinColumns=#JoinColumn(name="project_id"),
inverseJoinColumns=#JoinColumn(name="employee_id")
)
private List<Employee> employees;
public Project() {
}
public Project(String name, String stage, String description) {
super();
this.name = name;
this.stage = stage;
this.description = description;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public long getProjectId() {
return projectId;
}
public void setProjectId(long projectId) {
this.projectId = projectId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStage() {
return stage;
}
public void setStage(String stage) {
this.stage = stage;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
//convenience method
public void addEmployee(Employee emp) {
if(employees == null) {
employees = new ArrayList<>();
}
employees.add(emp);
}
}
Here's the error message:
Java HotSpot(TM) 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
{spring.web.resources.chain.cache=false, spring.web.resources.cache.period=0}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.0)
2020-12-06 19:57:50.893 INFO 8560 --- [ restartedMain] com.project1.PmaApplication : Starting PmaApplication using Java 14.0.2 on DESKTOP-C26F0I7 with PID 8560 (C:\Users\kashi\git\PMA-Application\PMA-Application\target\classes started by kashi in C:\Users\kashi\git\PMA-Application\PMA-Application)
2020-12-06 19:57:50.897 INFO 8560 --- [ restartedMain] com.project1.PmaApplication : No active profile set, falling back to default profiles: default
2020-12-06 19:57:50.975 INFO 8560 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-12-06 19:57:50.975 INFO 8560 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-12-06 19:57:51.832 INFO 8560 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-12-06 19:57:51.902 INFO 8560 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 59 ms. Found 2 JPA repository interfaces.
2020-12-06 19:57:52.673 INFO 8560 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-12-06 19:57:52.682 INFO 8560 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-12-06 19:57:52.683 INFO 8560 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.39]
2020-12-06 19:57:52.779 INFO 8560 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-12-06 19:57:52.779 INFO 8560 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1803 ms
2020-12-06 19:57:52.843 INFO 8560 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-12-06 19:57:52.977 INFO 8560 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-12-06 19:57:53.025 INFO 8560 --- [ restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:c7335b0f-bd3a-43dd-9628-9ea69397c416'
2020-12-06 19:57:53.116 INFO 8560 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-12-06 19:57:53.268 INFO 8560 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-12-06 19:57:53.381 INFO 8560 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-12-06 19:57:53.397 WARN 8560 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'version' in value "${version}"
2020-12-06 19:57:53.397 INFO 8560 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-12-06 19:57:53.460 INFO 8560 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.23.Final
2020-12-06 19:57:53.619 INFO 8560 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-12-06 19:57:53.752 INFO 8560 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-12-06 19:57:54.169 WARN 8560 --- [ restartedMain] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'entityManagerFactory': javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.project1.entities.Project]
2020-12-06 19:57:54.169 INFO 8560 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-12-06 19:57:54.389 WARN 8560 --- [ restartedMain] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-200]
2020-12-06 19:57:54.392 INFO 8560 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-12-06 19:57:54.400 INFO 8560 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2020-12-06 19:57:54.405 INFO 8560 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-12-06 19:57:54.439 INFO 8560 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-12-06 19:57:54.489 ERROR 8560 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'version' in value "${version}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1415) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925) ~[spring-context-5.3.1.jar:5.3.1]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588) ~[spring-context-5.3.1.jar:5.3.1]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298) ~[spring-boot-2.4.0.jar:2.4.0]
at com.project1.PmaApplication.main(PmaApplication.java:12) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.4.0.jar:2.4.0]
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'version' in value "${version}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175) ~[spring-context-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:931) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1308) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1287) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.1.jar:5.3.1]
... 23 common frames omitted
The parent tag right underneath the model version in the pom.xml file is underlined in red and when I hover over it it shows this.
Execution default-resources of goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources failed: newPosition < 0: (-1 < 0) (org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources:default-resources:process-resources)
org.apache.maven.plugin.PluginExecutionException: Execution default-resources of goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources failed: newPosition < 0: (-1 < 0)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:148)
at org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:332)
at org.eclipse.m2e.core.internal.embedder.MavenImpl.lambda$8(MavenImpl.java:1379)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:179)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:114)
at org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:1378)
at org.eclipse.m2e.core.project.configurator.MojoExecutionBuildParticipant.build(MojoExecutionBuildParticipant.java:54)
at org.eclipse.m2e.core.internal.builder.MavenBuilderImpl.build(MavenBuilderImpl.java:135)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$1.method(MavenBuilder.java:169)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$1.method(MavenBuilder.java:1)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.lambda$1(MavenBuilder.java:114)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:179)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:114)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.lambda$0(MavenBuilder.java:105)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:179)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:153)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:101)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.execute(MavenBuilder.java:88)
at org.eclipse.m2e.core.internal.builder.MavenBuilder.build(MavenBuilder.java:197)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:832)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:220)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:263)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:316)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:319)
at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:371)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:392)
at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:154)
at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:244)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
Caused by: java.lang.IllegalArgumentException: newPosition < 0: (-1 < 0)
at java.base/java.nio.Buffer.createPositionException(Buffer.java:334)
at java.base/java.nio.Buffer.position(Buffer.java:309)
at java.base/java.nio.ByteBuffer.position(ByteBuffer.java:1309)
at java.base/java.nio.ByteBuffer.position(ByteBuffer.java:266)
at org.apache.maven.shared.utils.io.FileUtils.copyFile(FileUtils.java:1946)
at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile(DefaultMavenFileFilter.java:98)
at org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering.filterResources(DefaultMavenResourcesFiltering.java:262)
at org.apache.maven.plugins.resources.ResourcesMojo.execute(ResourcesMojo.java:356)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
... 30 more
Here's the pom.xml file and the tag right underneath the model version
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.project1</groupId>
<artifactId>PMA-Application</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>PMA-Application</name>
<description>The PMA Web App</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I had the same exact problem, hope I can still help somebody with this.
If you're using eclipse go to
File > Properties > Java Build Path > Source
and now under src/main/resources at "Excluded" it said for me "**", make sure to delete this entry so that it sais "(None)". Fixed it for me.
add #PropertySource({"classpath:resource.properties"}) on your controller

#Document doesn't create a collection in spring boot application

I have a simple spring boot rest application. Trying to create a collection using #Document annotation in spring data mongo db. I know spring framework creates a collection if the document is denoted with #Document annotation.
Entity
#Document("User")
public class User {
#Id
private String Id;
#Field("firstName")
#TextIndexed
private String firstName;
#Field("lastName")
#TextIndexed
private String lastName;
private String address;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
properties
spring.data.mongodb.uri=mongodb://localhost:27017/Order
However, in the rest controller, it creates a collection on insert command, but still, it doesn't create a Text-index on insert.
#RestController
public class Controller {
private MongoTemplate mongoTemplate;
public Controller(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
#GetMapping("/get")
public String Get(){
mongoTemplate.insert(new User());
return "HelloWorld";
}
}
Don't have any error in the console as well
Console
2020-09-03 12:52:00.657 INFO 865 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication on macbooks-MacBook-Air.local with PID 865 (/Users/macbook/Projects/Fete/demo/build/classes/java/main started by macbook in /Users/macbook/Projects/Fete/demo)
2020-09-03 12:52:00.662 INFO 865 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2020-09-03 12:52:02.676 INFO 865 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2020-09-03 12:52:02.712 INFO 865 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 22ms. Found 0 MongoDB repository interfaces.
2020-09-03 12:52:04.106 INFO 865 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-09-03 12:52:04.136 INFO 865 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-09-03 12:52:04.137 INFO 865 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-09-03 12:52:04.269 INFO 865 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-09-03 12:52:04.270 INFO 865 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3500 ms
2020-09-03 12:52:04.558 INFO 865 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2020-09-03 12:52:04.692 INFO 865 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:9}] to localhost:27017
2020-09-03 12:52:04.731 INFO 865 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=8577619}
2020-09-03 12:52:06.165 INFO 865 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-03 12:52:06.746 INFO 865 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-09-03 12:52:06.764 INFO 865 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 6.69 seconds (JVM running for 13.238)
Code repository
https://github.com/anandjaisy/mongoDBSpringBoot
I have to set implicitly to work
In application.properties file
spring.data.mongodb.auto-index-creation=true
Or application.yml file
spring:
data:
mongodb:
auto-index-creation: true
Reference - Please use 'MongoMappingContext#setAutoIndexCreation(boolean)' or override 'MongoConfigurationSupport#autoIndexCreation()' to be explicit

cant connect to mysql databse using spring boot

When I am hitting url(http://localhost:8080/pjt/samples) in Postman for json data,it shows the following error.
{
"timestamp": "2020-05-17T10:54:26.705+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/pjt/samples"
}
1)pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>samplepjt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>samplepjt</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2)model:
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "samples")
public class Sample {
private Long id ;
private String name;
private String city;
public Sample(String name, String city) {
this.name = name;
this.city = city;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "city", nullable = false)
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "Sample [id=" + id + ",name=" + name + ", city=" + city + "]";
}
}
3)repository
package repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import model.Sample;
#Repository
public interface SampleRepository extends JpaRepository<Sample,Long>{
}
4)controller
package controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import model.Sample;
import repository.SampleRepository;
#RestController
#RequestMapping("/pjt")
public class SampleController {
#Autowired
private SampleRepository sampleRepository;
#PostMapping("/samples")
public Sample createSample(#Valid #RequestBody Sample sample) {
return sampleRepository.save(sample);
}
#GetMapping("/samples")
public List<Sample> getAllSample() {
return sampleRepository.findAll();
}
}
5)main function
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SamplepjtApplication {
public static void main(String[] args) {
SpringApplication.run(SamplepjtApplication.class, args);
}
}
6)application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/sampledb?useSSL=false
spring.datasource.username = root
spring.datasource.password = dali
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
. ____ _ __ _ _
/\ / ' __ _ ()_ __ __ _ \ \ \ \
( ( )_ | '_ | '| | ' / ` | \ \ \ \
\/ )| |)| | | | | || (| | ) ) ) )
' |____| .|| ||| |__, | / / / /
=========|_|==============|___/=///_/
:: Spring Boot :: (v2.2.7.RELEASE)
2020-05-17 16:47:56.159 INFO 3688 --- [ main] com.example.demo.SamplepjtApplication : No active profile set, falling back to default profiles: default
2020-05-17 16:47:58.395 INFO 3688 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-17 16:47:58.476 INFO 3688 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 49ms. Found 0 JPA repository interfaces.
2020-05-17 16:48:00.119 INFO 3688 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2020-05-17 16:48:00.142 INFO 3688 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-05-17 16:48:00.143 INFO 3688 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.34]
2020-05-17 16:48:00.496 INFO 3688 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-05-17 16:48:00.497 INFO 3688 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4199 ms
2020-05-17 16:48:00.980 INFO 3688 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-17 16:48:01.156 INFO 3688 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.15.Final
2020-05-17 16:48:01.579 INFO 3688 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-17 16:48:01.898 INFO 3688 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-17 16:48:02.714 INFO 3688 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-17 16:48:02.771 INFO 3688 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2020-05-17 16:48:03.635 INFO 3688 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation:[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-17 16:48:03.660 INFO 3688 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-17 16:48:04.042 WARN 3688 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-05-17 16:48:04.388 INFO 3688 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-17 16:48:04.845 INFO 3688 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2020-05-17 16:48:04.849 INFO 3688 --- [ main] com.example.demo.SamplepjtApplication : Started SamplepjtApplication in 9.906 seconds (JVM running for 12.757)
2020-05-17 16:48:13.367 INFO 3688 --- [nio-8081-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-05-17 16:48:13.369 INFO 3688 --- [nio-8081-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-05-17 16:48:13.395 INFO 3688 --- [nio-8081-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 25 ms
Can anyone help me to fix this issue?
You have to place the SampleController.java in com.example.demo.controller & SampleRepository.java in com.example.demo.repository. Or all the files should be in com.example.demo folder.
Because #SpringBootApplication has to scan all the components. Go through this doc for better understanding https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/html/using-boot-structuring-your-code.html.

Categories

Resources