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();
}
Related
I am trying to send below Jsonobject as request parameter to rest API.
{ "date": "2022-01-01", "value": [ "TST/USED" ] }
Value field contains the list of values, but when I add the value in this format as part of request it replaces string / to \/ due to which the request is not processing and it throws 415 : [no body] exception.
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add(AUTHORIZATION, "Bearer " + token);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
JSONObject req = new JSONObject();
req.put("date", "2022-01-01");
req.put("value", "TST/USED");
HttpEntity<Object> object = new HttpEntity<>(req.toString(), headers);
Object response = restTemplate.exchange(apiUrl, HttpMethod.POST, object, Object.class)
.getBody();
I don't see the issue you mention, here is what I am running:
Main application with Spring boot and a RestTemplate bean.
package com.so.so72424428;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class So72424428Application {
public static void main(String[] args) {
SpringApplication.run(So72424428Application.class, args);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
An api to test:
package com.so.so72424428;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ApiEndPoint {
#PostMapping(path = "/test-api", consumes = MimeTypeUtils.APPLICATION_JSON_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String echo (#RequestBody String jsonMessage) {
return jsonMessage;
}
}
A class to run your code:
package com.so.so72424428;
import java.util.Arrays;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import lombok.extern.slf4j.Slf4j;
#Component
#Slf4j
public class So72424428 implements CommandLineRunner {
#Autowired
private RestTemplate restTemplate;
#Override
public void run(String... args) throws Exception {
HttpHeaders headers = new HttpHeaders();
//headers.add(AUTHORIZATION, "Bearer " + token);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject req = new JSONObject();
req.put("date", "2022-01-01");
req.put("value", "TST/USED");
log.info(req.toString());
HttpEntity<Object> object = new HttpEntity<>(req.toString(), headers);
String apiUrl = "http://localhost:8080/test-api";
Object response = restTemplate.exchange(apiUrl, HttpMethod.POST, object, Object.class)
.getBody();
log.info(response.toString());
}
}
When I run the code I print out the content of the req variable:
{"date":"2022-01-01","value":"TST/USED"}
Also after round trip of the request I print out the response:
{date=2022-01-01, value=TST/USED}
This is the log:
2022-05-29 13:39:24.416 INFO 32332 --- [ restartedMain] com.so.so72424428.So72424428Application : Starting So72424428Application using Java 15.0.2 on ...)
2022-05-29 13:39:24.418 INFO 32332 --- [ restartedMain] com.so.so72424428.So72424428Application : No active profile set, falling back to 1 default profile: "default"
2022-05-29 13:39:24.462 INFO 32332 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-05-29 13:39:24.462 INFO 32332 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-05-29 13:39:25.310 INFO 32332 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-05-29 13:39:25.320 INFO 32332 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-05-29 13:39:25.320 INFO 32332 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-05-29 13:39:25.387 INFO 32332 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-05-29 13:39:25.388 INFO 32332 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 925 ms
2022-05-29 13:39:25.716 INFO 32332 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-05-29 13:39:25.760 INFO 32332 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-05-29 13:39:25.768 INFO 32332 --- [ restartedMain] com.so.so72424428.So72424428Application : Started So72424428Application in 1.678 seconds (JVM running for 2.616)
2022-05-29 13:39:25.778 INFO 32332 --- [ restartedMain] com.so.so72424428.So72424428 : {"date":"2022-01-01","value":"TST/USED"}
2022-05-29 13:39:25.869 INFO 32332 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-05-29 13:39:25.869 INFO 32332 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-05-29 13:39:25.870 INFO 32332 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2022-05-29 13:39:25.921 INFO 32332 --- [ restartedMain] com.so.so72424428.So72424428 : {date=2022-01-01, value=TST/USED}
2022-05-29 13:39:33.346 INFO 32332 --- [on(2)-127.0.0.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
As you can see there is no backslash, nor no issue for completing the request.
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
I am trying to use spring.gson.disable-html-escaping=false in my spring boot application.
but it is returning default value.
application.properties:
spring.mvc.converters.preferred-json-mapper=gson
spring.gson.disable-html-escaping=false
GsonHttpMessageConverterConfig.java
package com.example.demo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import java.util.*;
import java.util.stream.Collectors;
#Configuration
#Slf4j
public class GsonHttpMessageConverterConfig {
#Value("${grove.gson.http.converter.mediaTypes}")
private String configuredMediaTypes;
#Value("${spring.gson.disable-html-escaping}")
private String disabledHtmlEscaping;
#Bean
#Autowired
public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
List<MediaType> configuredMediaTypes = httpConverterMediaTypes();
if (!configuredMediaTypes.isEmpty()){
converter.setSupportedMediaTypes(configuredMediaTypes);
}
converter.setGson(gson());
System.out.println("converter.getGson().htmlSafe() : "+converter.getGson().htmlSafe());
return converter;
}
#Bean
public Gson gson() {
//String disabledHtmlEscaping = System.getenv("spring.gson.disable-html-escaping");
final GsonBuilder builder = new GsonBuilder();
System.out.println("spring.gson.disable-html-escaping : "+disabledHtmlEscaping);
return builder.create();
}
private List<MediaType> httpConverterMediaTypes(){
//String configuredMediaTypes = System.getenv("grove.gson.http.converter.mediaTypes");
if (configuredMediaTypes != null && !configuredMediaTypes.trim().equals("")){
return Arrays.stream(configuredMediaTypes.split(","))
.map(mediaType -> mediaType.split("/"))
.map(mediaType -> new MediaType(mediaType[0],mediaType[1]))
.collect(Collectors.toList());
}
return Collections.emptyList();
}
}
can somebody help me why that property is not working.
I dont want to use builder.disableHtmlEscaping().create()
output is :
2022-03-28 11:20:06.930 INFO 11920 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.60]
2022-03-28 11:20:06.980 INFO 11920 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-03-28 11:20:06.980 INFO 11920 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1290 ms
spring.gson.disable-html-escaping : false
converter.getGson().htmlSafe() : true
2022-03-28 11:20:07.730 INFO 11920 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-03-28 11:20:07.735 INFO 11920 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 13 endpoint(s) beneath base path '/actuator'
2022-03-28 11:20:07.774 INFO 11920 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-03-28 11:20:07.789 INFO 11920 --- [ restartedMain] com.example.demo.DemoApplication : Started DemoApplication in 2.566 seconds (JVM running for 2.965)
the expected output is :
converter.getGson().htmlSafe() is should return false if
Attempting to create a simple site that displays the content on my MySql database. I use the word attempting loosely lol. Notice the pages I have "/all" which I use to check if my list is empty. I'm trying to figure out why is my list empty and not storing the content of my database?
MySql:
CREATE DATABASE IF NOT EXISTS `web_customer_tracker`;
USE `web_customer_tracker`;
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer`(
`id` INT(11) NOT NULL auto_increment,
`first_name` VARCHAR(45) DEFAULT NULL,
`last_name` VARCHAR(45)DEFAULT NULL,
`email` VARCHAR(45) DEFAULT NULL,
PRIMARY KEY(`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 CHARSET=latin1;
INSERT INTO `customer` VALUES
(1, 'David', 'Adams', 'david#luv2code.com'),
(2, 'John', 'Die', 'john#luv2code.com'),
(3, 'Ajay', 'Rao', 'ajay#luv2code.com'),
(4, 'Mary', 'Publiidc', 'mary#luv2code.com'),
(5, 'Maxwell', 'Dixon', 'maxwell#luv2code.com');
Entity:
#Entity
#Table(name = "customer")
public class Customer implements Serializable {
#Column(name = "id")
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
public Customer(){}
public Customer(String firstName, String lastName, String company){
this.firstName = firstName;
this.lastName = lastName;
this.email = company;
}
#Override
public String toString() {
return "Customer{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.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 getCompany() {
return email;
}
public void setCompany(String company) {
this.email = company;
}
}
DAO
#Repository
#Transactional
public interface CustomerDAO extends CrudRepository<Customer, String> {
public List<Customer> findAll();
}
Impl:
#Transactional
#Repository
public abstract class CustomerDAOImpl implements CustomerDAO {
private CustomerDAO customerDAO;
#Override
public List<Customer> findAll() {
return customerDAO.findAll();
}
}
Controller:
#Controller
public class CustomerController {
#Autowired
private CustomerDAO customerDAO;
public String string;
#RequestMapping(value = "/list")
public String listCustomers(Model model){
List<Customer> customers = customerDAO.findAll();
String string = customers.get(1).toString();
model.addAttribute("text", string);
model.addAttribute("customers", customers);
return "list-customers";
}
#RequestMapping(value = "/all")
#ResponseBody
public String get() {
List<Customer> customers = customerDAO.findAll();
String names;
if(customers.isEmpty() == true){
names = "This is empty";
} else {
names = "Something is in here";
}
return names;
}
}
Stack Trace:
/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/bin/java -Didea.launcher.port=7536 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA CE.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/lib/tools.jar:/Users/ronald/IdeaProjects/springtutorial/target/classes:/Users/ronald/mysql-connector-java-5.1.41/mysql-connector-java-5.1.41-bin.jar:/Users/ronald/.m2/repository/org/springframework/boot/spring-boot-starter-thymeleaf/1.5.1.RELEASE/spring-boot-starter-thymeleaf-1.5.1.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/boot/spring-boot-starter/1.5.1.RELEASE/spring-boot-starter-1.5.1.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/boot/spring-boot/1.5.1.RELEASE/spring-boot-1.5.1.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.5.1.RELEASE/spring-boot-autoconfigure-1.5.1.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.5.1.RELEASE/spring-boot-starter-logging-1.5.1.RELEASE.jar:/Users/ronald/.m2/repository/ch/qos/logback/logback-classic/1.1.9/logback-classic-1.1.9.jar:/Users/ronald/.m2/repository/ch/qos/logback/logback-core/1.1.9/logback-core-1.1.9.jar:/Users/ronald/.m2/repository/org/slf4j/jul-to-slf4j/1.7.22/jul-to-slf4j-1.7.22.jar:/Users/ronald/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.22/log4j-over-slf4j-1.7.22.jar:/Users/ronald/.m2/repository/org/yaml/snakeyaml/1.17/snakeyaml-1.17.jar:/Users/ronald/.m2/repository/org/thymeleaf/thymeleaf-spring4/2.1.5.RELEASE/thymeleaf-spring4-2.1.5.RELEASE.jar:/Users/ronald/.m2/repository/nz/net/ultraq/thymeleaf/thymeleaf-layout-dialect/1.4.0/thymeleaf-layout-dialect-1.4.0.jar:/Users/ronald/.m2/repository/org/codehaus/groovy/groovy/2.4.7/groovy-2.4.7.jar:/Users/ronald/.m2/repository/org/springframework/boot/spring-boot-starter-web/1.5.1.RELEASE/spring-boot-starter-web-1.5.1.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/1.5.1.RELEASE/spring-boot-starter-tomcat-1.5.1.RELEASE.jar:/Users/ronald/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/8.5.11/tomcat-embed-websocket-8.5.11.jar:/Users/ronald/.m2/repository/org/hibernate/hibernate-validator/5.3.4.Final/hibernate-validator-5.3.4.Final.jar:/Users/ronald/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar:/Users/ronald/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.8.6/jackson-databind-2.8.6.jar:/Users/ronald/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.8.0/jackson-annotations-2.8.0.jar:/Users/ronald/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.8.6/jackson-core-2.8.6.jar:/Users/ronald/.m2/repository/org/springframework/spring-web/4.3.6.RELEASE/spring-web-4.3.6.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/spring-aop/4.3.6.RELEASE/spring-aop-4.3.6.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/spring-context/4.3.6.RELEASE/spring-context-4.3.6.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/spring-webmvc/4.3.6.RELEASE/spring-webmvc-4.3.6.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/spring-expression/4.3.6.RELEASE/spring-expression-4.3.6.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/spring-core/4.3.6.RELEASE/spring-core-4.3.6.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/spring-orm/4.3.7.RELEASE/spring-orm-4.3.7.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/spring-beans/4.3.6.RELEASE/spring-beans-4.3.6.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/spring-jdbc/4.3.6.RELEASE/spring-jdbc-4.3.6.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/spring-tx/4.3.6.RELEASE/spring-tx-4.3.6.RELEASE.jar:/Users/ronald/.m2/repository/org/hibernate/hibernate-core/5.2.9.Final/hibernate-core-5.2.9.Final.jar:/Users/ronald/.m2/repository/org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar:/Users/ronald/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar:/Users/ronald/.m2/repository/org/javassist/javassist/3.21.0-GA/javassist-3.21.0-GA.jar:/Users/ronald/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar:/Users/ronald/.m2/repository/org/jboss/spec/javax/transaction/jboss-transaction-api_1.2_spec/1.0.1.Final/jboss-transaction-api_1.2_spec-1.0.1.Final.jar:/Users/ronald/.m2/repository/org/jboss/jandex/2.0.3.Final/jandex-2.0.3.Final.jar:/Users/ronald/.m2/repository/com/fasterxml/classmate/1.3.3/classmate-1.3.3.jar:/Users/ronald/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar:/Users/ronald/.m2/repository/org/hibernate/common/hibernate-commons-annotations/5.0.1.Final/hibernate-commons-annotations-5.0.1.Final.jar:/Users/ronald/.m2/repository/mysql/mysql-connector-java/5.1.40/mysql-connector-java-5.1.40.jar:/Users/ronald/.m2/repository/c3p0/c3p0/0.9.1.2/c3p0-0.9.1.2.jar:/Users/ronald/.m2/repository/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar:/Users/ronald/.m2/repository/org/springframework/boot/spring-boot-starter-data-jpa/1.5.1.RELEASE/spring-boot-starter-data-jpa-1.5.1.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/boot/spring-boot-starter-aop/1.5.1.RELEASE/spring-boot-starter-aop-1.5.1.RELEASE.jar:/Users/ronald/.m2/repository/org/aspectj/aspectjweaver/1.8.9/aspectjweaver-1.8.9.jar:/Users/ronald/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/1.5.1.RELEASE/spring-boot-starter-jdbc-1.5.1.RELEASE.jar:/Users/ronald/.m2/repository/org/apache/tomcat/tomcat-jdbc/8.5.11/tomcat-jdbc-8.5.11.jar:/Users/ronald/.m2/repository/org/apache/tomcat/tomcat-juli/8.5.11/tomcat-juli-8.5.11.jar:/Users/ronald/.m2/repository/org/hibernate/hibernate-entitymanager/5.0.11.Final/hibernate-entitymanager-5.0.11.Final.jar:/Users/ronald/.m2/repository/javax/transaction/javax.transaction-api/1.2/javax.transaction-api-1.2.jar:/Users/ronald/.m2/repository/org/springframework/data/spring-data-jpa/1.11.0.RELEASE/spring-data-jpa-1.11.0.RELEASE.jar:/Users/ronald/.m2/repository/org/springframework/data/spring-data-commons/1.13.0.RELEASE/spring-data-commons-1.13.0.RELEASE.jar:/Users/ronald/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.22/jcl-over-slf4j-1.7.22.jar:/Users/ronald/.m2/repository/org/springframework/spring-aspects/4.3.6.RELEASE/spring-aspects-4.3.6.RELEASE.jar:/Users/ronald/.m2/repository/org/thymeleaf/thymeleaf-spring3/3.0.3.RELEASE/thymeleaf-spring3-3.0.3.RELEASE.jar:/Users/ronald/.m2/repository/org/thymeleaf/thymeleaf/2.1.5.RELEASE/thymeleaf-2.1.5.RELEASE.jar:/Users/ronald/.m2/repository/org/unbescape/unbescape/1.1.0.RELEASE/unbescape-1.1.0.RELEASE.jar:/Users/ronald/.m2/repository/org/slf4j/slf4j-api/1.7.22/slf4j-api-1.7.22.jar:/Users/ronald/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.5.11/tomcat-embed-core-8.5.11.jar:/Users/ronald/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/8.5.11/tomcat-embed-el-8.5.11.jar:/Users/ronald/.m2/repository/javax/servlet/jstl/1.2/jstl-1.2.jar:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain com.luv2code.springtutorial.Application
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.1.RELEASE)
2017-04-16 20:11:51.726 INFO 8023 --- [ main] com.luv2code.springtutorial.Application : Starting Application on Ronalds-MacBook-Pro.local with PID 8023 (/Users/ronald/IdeaProjects/springtutorial/target/classes started by ronald in /Users/ronald/IdeaProjects/springtutorial)
2017-04-16 20:11:51.729 INFO 8023 --- [ main] com.luv2code.springtutorial.Application : No active profile set, falling back to default profiles: default
2017-04-16 20:11:52.009 INFO 8023 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4f9a3314: startup date [Sun Apr 16 20:11:52 EDT 2017]; root of context hierarchy
2017-04-16 20:11:53.416 INFO 8023 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration' of type [class org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-04-16 20:11:53.517 INFO 8023 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'validator' of type [class org.springframework.validation.beanvalidation.LocalValidatorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-04-16 20:11:53.579 INFO 8023 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$84f7773b] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-04-16 20:11:54.026 INFO 8023 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-04-16 20:11:54.050 INFO 8023 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-04-16 20:11:54.051 INFO 8023 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.11
2017-04-16 20:11:54.217 INFO 8023 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-04-16 20:11:54.218 INFO 8023 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2212 ms
2017-04-16 20:11:54.424 INFO 8023 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-04-16 20:11:54.431 INFO 8023 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-04-16 20:11:54.432 INFO 8023 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-04-16 20:11:54.432 INFO 8023 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-04-16 20:11:54.432 INFO 8023 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-04-16 20:11:55.310 INFO 8023 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-04-16 20:11:55.339 INFO 8023 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-04-16 20:11:55.420 INFO 8023 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.9.Final}
2017-04-16 20:11:55.422 INFO 8023 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-04-16 20:11:55.607 INFO 8023 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-04-16 20:11:55.739 INFO 8023 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-04-16 20:11:56.398 INFO 8023 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#1e225820'
2017-04-16 20:11:56.403 INFO 8023 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-04-16 20:11:57.156 INFO 8023 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4f9a3314: startup date [Sun Apr 16 20:11:52 EDT 2017]; root of context hierarchy
2017-04-16 20:11:57.276 INFO 8023 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/all]}" onto public java.lang.String com.luv2code.springtutorial.controller.CustomerController.get()
2017-04-16 20:11:57.278 INFO 8023 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/list]}" onto public java.lang.String com.luv2code.springtutorial.controller.CustomerController.listCustomers(org.springframework.ui.Model)
2017-04-16 20:11:57.283 INFO 8023 --- [ 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)
2017-04-16 20:11:57.284 INFO 8023 --- [ 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)
2017-04-16 20:11:57.342 INFO 8023 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-04-16 20:11:57.342 INFO 8023 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-04-16 20:11:57.425 INFO 8023 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-04-16 20:11:58.236 INFO 8023 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-04-16 20:11:58.335 INFO 8023 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-04-16 20:11:58.342 INFO 8023 --- [ main] com.luv2code.springtutorial.Application : Started Application in 17.231 seconds (JVM running for 17.958)
2017-04-16 20:12:03.155 INFO 8023 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-04-16 20:12:03.155 INFO 8023 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-04-16 20:12:03.176 INFO 8023 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 21 ms
2017-04-16 20:12:04.403 INFO 8023 --- [nio-8080-exec-2] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
First things first ,
Make sure you have done the below things.
You do not need CustomerDAOImpl, remove it.
In CustomerDAO change <Customer,String> to <Customer,Integer>
Again in the same interface remove #Transactional and #Repository, they are not required.
Rest of the code looks just fine. Try the above steps.
Thank you
suppose you remove the CustomerDAOImpl class and see.
You only need the Entity class (Customer) , Repository interface (CustomerDAO) which extendsCrudRepository<Customer, int> and the controller.
Sorry, if i am not wrong then where is your entitymanager and other database operation to fetch the list(). I mean where is the logic to fetch data.
your return customerDAO.findAll(); did nothing at all.you just calling method and no other things actually.
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;
...
}