cant connect to mysql databse using spring boot - java

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.

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

Failed to initialize JPA EntityManagerFactory: Use of #OneToMany or #ManyToMany targeting an unmapped class

i would like to join 3 tables by using #ManyToMany , I have 2 entities "user" and "roles" ,
like this
but it's gives me as an error :
Failed to initialize JPA EntityManagerFactory: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.example.demo.User.roles[com.example.demo.Role]
THe "user" entity :
package com.example.demo;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.JoinColumn;
#Entity
#Table(name="users")
public class User {
#Id
#Column(name = "role_id")
//pour l'auto-incrémentation de la clé primaire
////Strategy = GenerationType. IDENTITY : La génération de la clé primaire se fera à partir d’une Identité propre au SGBD.
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id ;
private String full_name;
private String password ;
private boolean enabled ;
private boolean email ;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
//pour connecter les tables
#JoinTable(
name = "users_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id")
)
private Set<Role> roles = new HashSet<>();
public String getUsername() {
return full_name ;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public boolean isEmail() {
return email;
}
public void setEmail(boolean email) {
this.email = email;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String full_name) {
this.full_name = full_name;
}
}
the "roles" entity :
package com.example.demo;
import javax.persistence.*;
#Entity
#Table(name = "roles")
public class Role {
#Id
#Column(name = "role_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
public String getName() {
return name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
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.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>16</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
the stack traces :
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.4)
2021-03-24 16:37:55.741 INFO 3784 --- [ restartedMain] com.example.demo.DemoApplication : Starting DemoApplication using Java 15.0.2 on DESKTOP-3TAPOK7 with
PID 3784 (E:\Stage\demo\target\classes started by Dell in E:\Stage\demo)
2021-03-24 16:37:55.743 INFO 3784 --- [ restartedMain] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2021-03-24 16:37:55.798 INFO 3784 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-03-24 16:37:55.799 INFO 3784 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-03-24 16:37:56.411 INFO 3784 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-03-24 16:37:56.464 INFO 3784 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 41 ms. Found 1 JPA repository interfaces.
2021-03-24 16:37:57.087 INFO 3784 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-03-24 16:37:57.105 INFO 3784 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-03-24 16:37:57.105 INFO 3784 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.44]
2021-03-24 16:37:57.224 INFO 3784 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-03-24 16:37:57.224 INFO 3784 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1425 ms
2021-03-24 16:37:57.404 INFO 3784 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-03-24 16:37:57.461 INFO 3784 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.29.Final
2021-03-24 16:37:57.569 INFO 3784 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-03-24 16:37:57.642 INFO 3784 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-03-24 16:37:57.725 INFO 3784 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-03-24 16:37:57.781 INFO 3784 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL92Dialect2021-03-24 16:37:57.967 ERROR 3784 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.example.demo.User.roles[com.example.demo.Role]
2021-03-24 16:37:57.967 WARN 3784 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of
#OneToMany or #ManyToMany targeting an unmapped class: com.example.demo.User.roles[com.example.demo.Role]
2021-03-24 16:37:57.976 INFO 3784 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-03-24 16:37:58.013 INFO 3784 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2021-03-24 16:37:58.016 INFO 3784 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-03-24 16:37:58.028 INFO 3784 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-03-24 16:37:58.046 ERROR 3784 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.example.demo.User.roles[com.example.demo.Role]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.5.jar:5.3.5]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.5.jar:5.3.5]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.5.jar:5.3.5]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.5.jar:5.3.5]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.5.jar:5.3.5]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.5.jar:5.3.5]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.5.jar:5.3.5]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.5.jar:5.3.5]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.5.jar:5.3.5]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.5.jar:5.3.5]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.4.jar:2.4.4]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:769) ~[spring-boot-2.4.4.jar:2.4.4]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) ~[spring-boot-2.4.4.jar:2.4.4]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) ~[spring-boot-2.4.4.jar:2.4.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) ~[spring-boot-2.4.4.jar:2.4.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1313) ~[spring-boot-2.4.4.jar:2.4.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-2.4.4.jar:2.4.4]
at com.example.demo.DemoApplication.main(DemoApplication.java:10) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[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.4.jar:2.4.4]
Caused by: org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.example.demo.User.roles[com.example.demo.Role]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1351) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:874) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:799) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:53) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1693) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1661) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:295) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1224) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1255) ~[hibernate-core-5.4.29.Final.jar:5.4.29.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58)
~[spring-orm-5.3.5.jar:5.3.5]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.5.jar:5.3.5]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.5.jar:5.3.5]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.5.jar:5.3.5]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.5.jar:5.3.5]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845) ~[spring-beans-5.3.5.jar:5.3.5]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782) ~[spring-beans-5.3.5.jar:5.3.5]
... 22 common frames omitted
mvn spring-boot:r
Thanks in advance.

Can't connect Spring boot with MongoDb

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.

Post and Get not mapped to Spring boot - status : 404

I have a simple application to test Spring Boot.
Below is the configuration and the packages are set as per Spring documentation.
There is no error in application startup. Using Spring boot with eclipse.
Still the controller is not mapped to the server and when I do Post or Get it says :
{
"timestamp": 1547026379146,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/postdata"
}
Repository:
package com.abc.nice.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.abc.nice.entity.Messages;
#Repository
public interface MessagesRepository extends JpaRepository<Messages, Long> {
}
Entity:
package com.abc.nice.entity;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.CascadeType;
import javax.persistence.Column;
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.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name = "Messages")
public class Messages{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Size(max = 100)
private String toNumber;
#Size(max = 250)
private String hsm;
#Size(max = 250)
private String template;
#Size(max = 250)
private String parameters;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTo() {
return toNumber;
}
public void setTo(String toNumber) {
this.toNumber = toNumber;
}
public String getHsm() {
return hsm;
}
public void setHsm(String hsm) {
this.hsm = hsm;
}
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
public String getParameters() {
return parameters;
}
public void setParameters(String parameters) {
this.parameters = parameters;
}
}
Controller :
package com.abc.nice.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import org.springframework.web.client.RestTemplate;
import com.abc.nice.entity.Messages;
import com.abc.nice.repo.MessagesRepository;
#RestController
public class ControllerRest {
#Autowired
private Messages msgDao;
private MessagesRepository msgRepo;
RestTemplate restTemplate;
#GetMapping({ "/StatusData" })
public List<Messages> index() {
return this.msgRepo.findAll();
}
#PostMapping(path = {"/postdata"})
public ResponseEntity<Messages> createBody(#RequestBody Map<String, String> body) {
this.msgDao = new Messages();
this.msgDao.setTemplate((String) body.get("template"));
this.msgDao.setParameters((String) body.get("parameters"));
this.msgDao.setHsm((String) body.get("hsm"));
this.msgDao.setTo((String) body.get("to"));
return new ResponseEntity<Messages>(this.msgRepo.save(this.msgDao), HttpStatus.OK);
}
}
MainClass :
package com.abc.nice;
import org.hibernate.HibernateException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
//#EntityScan("com.abc.nice.entity")
#ComponentScan({"com.abc.nice.entity","com.abc.nice.controller"})
#EnableJpaRepositories({"com.abc.nice.repo"})
//#EnableAutoConfiguration
public class TestApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(TestApplication .class, args);
}
}
Startup Log :
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.9.RELEASE)
2019-01-09 17:33:27.724 INFO 19732 --- [ main] com.abc.nice.TestApplication : Starting TestApplication on abcD02 with PID 19732 (C:\Users\abcd\Desktop\test\target\classes started by abcD in C:\Users\abcd\Desktop\test)
2019-01-09 17:33:27.728 INFO 19732 --- [ main] com.abc.nice.TestApplication : No active profile set, falling back to default profiles: default
2019-01-09 17:33:27.827 INFO 19732 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4206a205: startup date [Wed Jan 09 17:33:27 SGT 2019]; root of context hierarchy
2019-01-09 17:33:29.489 INFO 19732 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-01-09 17:33:29.506 INFO 19732 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-01-09 17:33:29.507 INFO 19732 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
2019-01-09 17:33:29.746 INFO 19732 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-01-09 17:33:29.746 INFO 19732 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1922 ms
2019-01-09 17:33:30.005 INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2019-01-09 17:33:30.009 INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-01-09 17:33:30.009 INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-01-09 17:33:30.009 INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-01-09 17:33:30.009 INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2019-01-09 17:33:30.598 INFO 19732 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2019-01-09 17:33:30.610 INFO 19732 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-01-09 17:33:30.680 INFO 19732 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2019-01-09 17:33:30.682 INFO 19732 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-01-09 17:33:30.683 INFO 19732 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2019-01-09 17:33:30.749 INFO 19732 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2019-01-09 17:33:30.864 INFO 19732 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-01-09 17:33:31.033 INFO 19732 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2019-01-09 17:33:31.058 INFO 19732 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-01-09 17:33:31.388 INFO 19732 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4206a205: startup date [Wed Jan 09 17:33:27 SGT 2019]; root of context hierarchy
2019-01-09 17:33:31.454 INFO 19732 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-01-09 17:33:31.455 INFO 19732 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-01-09 17:33:31.489 INFO 19732 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-09 17:33:31.489 INFO 19732 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-09 17:33:31.527 INFO 19732 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-09 17:33:31.866 INFO 19732 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2019-01-09 17:33:31.937 INFO 19732 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2019-01-09 17:33:31.942 INFO 19732 --- [ main] com.abc.nice.WhatsapptestApplication : Started WhatsapptestApplication in 4.532 seconds (JVM running for 6.213)
2019-01-09 17:39:45.612 INFO 19732 --- [on(2)-127.0.0.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
2019-01-09 17:39:45.613 INFO 19732 --- [on(2)-127.0.0.1] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4206a205: startup date [Wed Jan 09 17:33:27 SGT 2019]; root of context hierarchy
2019-01-09 17:39:45.616 INFO 19732 --- [on(2)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2019-01-09 17:39:45.617 INFO 19732 --- [on(2)-127.0.0.1] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
Application.properties:
#spring.datasource.type=org.apache.commons.dbcp.BasicDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/ptpreconn?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.data.jpa.repositories.enabled=true
#spring.jpa.database-platform=org.hibernate.dialect.MYSQL5Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
server.port=${PORT:8080}
Please attach request from e.g. the developers' tools with HTTP verb that you are using and exact response from that request. I am concerned about #GetMapping - why it is in curly braces?
About post mapping, maybe you should describe consumes and produces part of mapping?
E.g.
#PostMapping(path = "/members", consumes = "application/json", produces = "application/json")
I have never used #PostMapping annotation without those parts.
UPDATE:
After removal of unnecessary component scan in Main class change controller as follow:
#RestController
public class ControllerRest {
#Autowired
private MessagesRepository msgRepo;
RestTemplate restTemplate;
#GetMapping({ "/StatusData" })
public List<Messages> index() {
return this.msgRepo.findAll();
}
#PostMapping(path = {"/postdata"})
public ResponseEntity<Messages> createBody(#RequestBody Map<String, String> body) {
Messages msgDao = new Messages();
msgDao.setTemplate((String) body.get("template"));
msgDao.setParameters((String) body.get("parameters"));
msgDao.setHsm((String) body.get("hsm"));
msgDao.setTo((String) body.get("to"));
return new ResponseEntity<Messages>(this.msgRepo.save(this.HttpStatus.OK);
}
}
Add a context path to your application.properties file or application.yml, whichever you are using.
server.servlet.contextPath=/springbootapi
Hit your endpoint: The endpoint for your POST method will be:
http://localhost:{PORT}/springbootapi/postdata
Why dont you statically supply your port. I think the port should be something like:
server.port=8080
I don't understand why you using #RequestBody with "Map<String,String>".
Try this code :
#Autowired
private MessagesRepository msgRepo;
#PostMapping("/postdata")
public ResponseEntity<Object> createBody(#RequestBody Message message) {
Message saveMessage= msgRepo.save(message);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(saveMessage.getId()).toUri();
return ResponseEntity.created(location).build();
}

Hibernate not creating Table automatically in spring boot using postgresql

I want to save data to a table in postgresql. I am using spring boot + postgresql along with hibernate. My Application does not have any error but it is not creating table in database.
This is my controller class
package com.ge.health.poc.controlleer;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ge.health.poc.model.Bookmodel;
import com.ge.health.poc.service.BookServiceImplementation;
#RestController
public class HttpController {
#Autowired
BookServiceImplementation bookserviceimpl;
#RequestMapping(value = "/httpmethod", method = RequestMethod.POST)
#ResponseBody
public void helloService(#RequestBody String input) throws JsonParseException, JsonMappingException, IOException {
System.out.println(input);
ObjectMapper mapper = new ObjectMapper();
Bookmodel pojodata = mapper.readValue(input, Bookmodel.class);
System.out.println(pojodata);
}
}
AppConfig.java
package com.ge.health.poc.configuration;
import java.util.Properties;
import javax.annotation.Resource;
import javax.jms.ConnectionFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
public class AppConfig {
#Resource
private SettingConfig settings;
#Bean
JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
return new JmsTemplate(connectionFactory);
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(settings.getDriverClassName());
dataSource.setUrl(settings.getDatasource());
dataSource.setUsername(settings.getUsername());
dataSource.setPassword(settings.getPassword());
return dataSource;
}
/**
* Declare the JPA entity manager factory.
*/
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
// Hibernate properties
Properties additionalProperties = new Properties();
additionalProperties.put("hibernate.dialect", settings.getDialect());
additionalProperties.put("hibernate.show_sql", settings.getShowsql());
additionalProperties.put("hibernate.hbm2ddl.auto", settings.getDdlauto());
entityManagerFactory.setJpaProperties(additionalProperties);
return entityManagerFactory;
}
/**
* Declare the transaction manager.
*/
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
/**
* PersistenceExceptionTranslationPostProcessor is a bean post processor
* which adds an advisor to any bean annotated with Repository so that any
* platform-specific exceptions are caught and then rethrown as one Spring's
* unchecked data access exceptions (i.e. a subclass of
* DataAccessException).
*/
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
SettingConfig.java
package com.ge.health.poc.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class SettingConfig {
public String getDdlauto() {
return ddlauto;
}
public void setDdlauto(String ddlauto) {
this.ddlauto = ddlauto;
}
public String getShowsql() {
return showsql;
}
public void setShowsql(String showsql) {
this.showsql = showsql;
}
public String getDialect() {
return dialect;
}
public void setDialect(String dialect) {
this.dialect = dialect;
}
#Value("${spring.datasource.url}")
private String datasource;
#Value("${hibernate.hbm2ddl.auto}")
private String ddlauto;
#Value("${hibernate.show_sql}")
private String showsql;
#Value("{hibernate.dialect}")
private String dialect;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
#Value("${spring.datasource.driver-class-name}")
private String driverClassName;
public String getDatasource() {
return datasource;
}
public void setDatasource(String datasource) {
this.datasource = datasource;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
}
application.properties
# Database
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/bookdetails
spring.datasource.username=postgres
spring.datasource.password=admin
# Hibernate
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create
POJO class
package com.ge.health.poc.model;
import javax.persistence.Column;
import javax.persistence.Table;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Component;
#Component
#Table
public class Bookmodel {
#Id
private String id;
#Column
private String name;
#Column
private String isbn;
#Column
private String author;
#Column
private String pages;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPages() {
return pages;
}
public void setPages(String pages) {
this.pages = pages;
}
#Override
public String toString() {
return "Bookmodel [id=" + id + ", name=" + name + ", isbn=" + isbn + ", author=" + author + ", pages=" + pages
+ "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
I want to save data to a table in postgresql.I am using spring boot + postgresql along with hibernate. My Application donot have any error but it is not creating table in database.
The problem is that you are using wrong annotation i.e #component.
Remove this annotation and use #Entity.
This is your code.
After executing this code check the logs, you will see no sql create query is fired by hibernate.
package com.example.demo.hibernateDemoEntity;
import javax.persistence.*;
import org.springframework.stereotype.Component;
#Component
#Table
public class Bookmodel {
#Id
private int id;
#Column
private String name;
#Column
private String isbn;
#Column
private String author;
#Column
private String pages;
}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.7.RELEASE)
2019-09-01 16:52:15.532 INFO 5436 --- [ main] c.example.demo.HibernateDemoApplication : Starting HibernateDemoApplication on BGINMAC004.local with PID 5436 (/Users/Dildeep.Singh/Documents/workspace-sts-3.9.9.RELEASE/HibernateDemo/target/classes started by Dildeep.Singh in /Users/Dildeep.Singh/Documents/workspace-sts-3.9.9.RELEASE/HibernateDemo)
2019-09-01 16:52:15.536 INFO 5436 --- [ main] c.example.demo.HibernateDemoApplication : No active profile set, falling back to default profiles: default
2019-09-01 16:52:16.331 INFO 5436 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-09-01 16:52:16.350 INFO 5436 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 12ms. Found 0 repository interfaces.
2019-09-01 16:52:16.730 INFO 5436 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$de6750d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-09-01 16:52:17.026 INFO 5436 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-09-01 16:52:17.049 INFO 5436 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-09-01 16:52:17.050 INFO 5436 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.22]
2019-09-01 16:52:17.156 INFO 5436 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-09-01 16:52:17.156 INFO 5436 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1581 ms
2019-09-01 16:52:17.355 INFO 5436 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-09-01 16:52:17.805 INFO 5436 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-09-01 16:52:17.844 INFO 5436 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-09-01 16:52:17.894 INFO 5436 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.10.Final}
2019-09-01 16:52:17.895 INFO 5436 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-09-01 16:52:18.056 INFO 5436 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-09-01 16:52:18.147 INFO 5436 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-09-01 16:52:18.388 INFO 5436 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#43a09ce2'
2019-09-01 16:52:18.390 INFO 5436 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-09-01 16:52:18.657 INFO 5436 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-01 16:52:18.690 WARN 5436 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : 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
2019-09-01 16:52:18.883 INFO 5436 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-09-01 16:52:18.886 INFO 5436 --- [ main] c.example.demo.HibernateDemoApplication : Started HibernateDemoApplication in 18.83 seconds (JVM running for 24.343)
Now replace #Component with #Entity annotation and see the logs.
#Entity
#Table
public class Bookmodel {
#Id
private int id;
#Column
private String name;
#Column
private String isbn;
#Column
private String author;
#Column
private String pages;
}
Spring Logs
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.7.RELEASE)
2019-09-01 17:10:59.943 INFO 5461 --- [ main] c.example.demo.HibernateDemoApplication : Starting HibernateDemoApplication on BGINMAC004.local with PID 5461 (/Users/Dildeep.Singh/Documents/workspace-sts-3.9.9.RELEASE/HibernateDemo/target/classes started by Dildeep.Singh in /Users/Dildeep.Singh/Documents/workspace-sts-3.9.9.RELEASE/HibernateDemo)
2019-09-01 17:10:59.946 INFO 5461 --- [ main] c.example.demo.HibernateDemoApplication : No active profile set, falling back to default profiles: default
2019-09-01 17:11:00.629 INFO 5461 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-09-01 17:11:00.649 INFO 5461 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 13ms. Found 0 repository interfaces.
2019-09-01 17:11:00.996 INFO 5461 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d77725a9] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-09-01 17:11:01.227 INFO 5461 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-09-01 17:11:01.249 INFO 5461 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-09-01 17:11:01.249 INFO 5461 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.22]
2019-09-01 17:11:01.357 INFO 5461 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-09-01 17:11:01.357 INFO 5461 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1374 ms
2019-09-01 17:11:01.519 INFO 5461 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-09-01 17:11:01.919 INFO 5461 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-09-01 17:11:01.958 INFO 5461 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-09-01 17:11:02.006 INFO 5461 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.10.Final}
2019-09-01 17:11:02.010 INFO 5461 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-09-01 17:11:02.182 INFO 5461 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-09-01 17:11:02.283 INFO 5461 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
**Hibernate: drop table if exists bookmodel
Hibernate: create table bookmodel (id integer not null, author varchar(255), isbn varchar(255), name varchar(255), pages varchar(255), primary key (id)) engine=MyISAM**
2019-09-01 17:11:02.893 INFO 5461 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#134f8ef6'
2019-09-01 17:11:02.895 INFO 5461 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-09-01 17:11:03.209 INFO 5461 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-01 17:11:03.239 WARN 5461 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : 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
2019-09-01 17:11:03.442 INFO 5461 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-09-01 17:11:03.445 INFO 5461 --- [ main] c.example.demo.HibernateDemoApplication : Started HibernateDemoApplication in 18.81 seconds (JVM running for 24.307)
Now you can see sql create query is fired by hibernate.
You are "using" Spring Boot and the first thing you do is try very hard not to use Spring Boot.
Instead of doing all the configuration by yourself let Spring Boot do the heavy lifting for you.
In your application.properties set the proper dialect and use the correct properties (see this section of the Spring Boot Reference Guide for a full list of properties).
# Database
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/bookdetails
spring.datasource.username=postgres
spring.datasource.password=admin
# Hibernate
spring.jpa.database=org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
And remove your custom configuration (i.e. the AppConfig and SettingConfig) that breaks the auto configuration of Spring Boot.
I don't see any column definition in your POJO, how do you expect hibernate to know what type of column to create by simply give a Java type such as String? For my MySQL database I would define POJO like this
#Component
#Table(name = "Book")
public class Bookmodel {
#Size(max = 32)
#Id
#Column(columnDefinition = "varchar(128)", nullable = false, unique = true)
private String id;
#Column(columnDefinition = "varchar(128)", nullable = false)
private String name;
...
}

Categories

Resources