I'm trying to return a list of values from JDBC but multiple columns of the database to solve this I just made a JSON object to make something like this
{
"Results 1": {
"IP": "192.168.1.2",
"Port": "13442",
"Domain": "google.com"
},
"Results 2": {
"IP": "192.168.1.2",
"Port": "13442",
"Domain": "google.com"
}
}
The issue is im getting this error WARN 43953 --- [nio-1900-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
What I've tried
I've tried using a hash map but it doesn't work and I don't even know if it can return the value like a want it.
What I hope
I hope at the end I can get a list of values similar to the way I showed above, all separate. This is to be displayed on HTML later so if I'm doing something i shouldn't also let me know
This is my code
package com.mchugo.que.McHugoQue.Controller;
import com.mchugo.que.McHugoQue.Models.ConnectionDetails;
import com.mchugo.que.McHugoQue.Models.SearchCredential;
import com.mysql.cj.xdevapi.JsonArray;
import org.json.JSONObject;
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.RestController;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
#RestController
public class ApiController {
#RequestMapping(value={"/search/credential", "xyz"}, method={RequestMethod.POST,RequestMethod.PUT, RequestMethod.GET})
public JsonArray searchCredential(#RequestBody SearchCredential searchCredential){
Connection connection = null;
Statement st = null;
ResultSet rs = null;
String Username = searchCredential.getUsername();
//grabs connection details
ConnectionDetails connectionDetails = new ConnectionDetails();
String username = "";
String password = "";
JsonArray array = new JsonArray();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + connectionDetails.getHost() + "/" + connectionDetails.getDatabase(), connectionDetails.getUsername(), connectionDetails.getPassword());
Statement statement = con.createStatement();
ResultSet res = statement.executeQuery("SELECT * FROM credentials WHERE identifier = '" + Username + "'");
while(res.next()){
JSONObject data = new JSONObject();
username = res.getString("identifier");
password = res.getString("password");
data.put("Username", username);
data.put("Password", password);
array.add(data);
}
}
catch(Exception ex){
System.out.println("Exception : " + ex.toString());
}
System.out.println(array);
return(array);
}
}
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.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mchugo.que</groupId>
<artifactId>McHugoQue</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>McHugoQue</name>
<description>Que for sending data to email for the compermised passwords</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
<version>0.0.20131108.vaadin1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
<version>0.0.20131108.vaadin1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>1.6.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.ws/jaxws-api -->
<dependency>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.10.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
What I tried
HashMap<String, String> data = new HashMap<>();
for(int i = 0; i <= 10; i++){
HashMap<String, String> data1 = new HashMap<>();
data1.put("IP", i + "");
data1.put("PORT", i + 1 + "");
data.put("value " + i, data1);
}
System.out.println(data);
Traceback
2022-04-15 13:22:08.415 INFO 43953 --- [ main] c.m.que.McHugoQue.McHugoQueApplication : Starting McHugoQueApplication using Java 16.0.1 on Macbook-Air.lan with PID 43953 (/Volumes/Drive/FiverrWork/untitled folder/McHugoQue/target/classes started by danielcaminero in /Volumes/Drive/FiverrWork/untitled folder/McHugoQue)
2022-04-15 13:22:08.419 INFO 43953 --- [ main] c.m.que.McHugoQue.McHugoQueApplication : No active profile set, falling back to 1 default profile: "default"
2022-04-15 13:22:10.677 INFO 43953 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 1900 (http)
2022-04-15 13:22:10.698 INFO 43953 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-04-15 13:22:10.698 INFO 43953 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.60]
2022-04-15 13:22:10.852 INFO 43953 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-04-15 13:22:10.852 INFO 43953 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2295 ms
2022-04-15 13:22:11.513 INFO 43953 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 1900 (http) with context path ''
2022-04-15 13:22:11.535 INFO 43953 --- [ main] c.m.que.McHugoQue.McHugoQueApplication : Started McHugoQueApplication in 4.137 seconds (JVM running for 5.008)
2022-04-15 13:22:21.712 INFO 43953 --- [nio-1900-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-04-15 13:22:21.712 INFO 43953 --- [nio-1900-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-04-15 13:22:21.713 INFO 43953 --- [nio-1900-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
{"Value 1":{"Username":"johnsen#cityeyes.dk","Password":"nodea03"}}
2022-04-15 13:22:22.181 WARN 43953 --- [nio-1900-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
You should work with a List instead putting the values inside an object and increasing the counter variable. I would suggest you use something like this
....
//grabs connection details
ConnectionDetails connectionDetails = new ConnectionDetails();
String username = "";
String password = "";
JSONArray array = new JSONArray();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + connectionDetails.getHost() + "/" + connectionDetails.getDatabase(), connectionDetails.getUsername(), connectionDetails.getPassword());
Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT * FROM credentials WHERE identifier = '" + Username + "'");
while(res.next()){
JSONObject data = new JSONObject();
String username = res.getString("identifier");
String password = res.getString("password");
data.put("Username", username);
data.put("Password", password);
array.add(data);
}
}
catch(Exception ex){
System.out.println("Exception : " + ex.toString());
}
System.out.println(data);
return(data);
Your output will look slightly different.
[
{
"Username: "firstUserName",
"Password": "somePass"
},
{
"Username: "secondUserName",
"Password": "someOtherPass"
}
]
It is however better to work with lists/arrays. Otherwise you wold have to access your result by incrementing variables until an error is thrown or something like this.
Related
I'm new to Spring Boot and want to build a food delivery API. The application was working perfectly fine but then when I created entities to add database functionality, the application stopped running. I tried debugging the code but I'm not sure where the problem is.
This is the log after I try to run the application.
2022-04-28 11:11:15.381 INFO 18796 --- [ main] c.s.f.FoodDeliveryApplication : No active profile set, falling back to 1 default profile: "default"
2022-04-28 11:11:16.197 INFO 18796 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-04-28 11:11:16.220 INFO 18796 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10 ms. Found 0 JPA repository interfaces.
2022-04-28 11:11:17.163 INFO 18796 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-04-28 11:11:17.176 INFO 18796 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-04-28 11:11:17.177 INFO 18796 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.62]
2022-04-28 11:11:17.356 INFO 18796 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-04-28 11:11:17.357 INFO 18796 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1901 ms
2022-04-28 11:11:17.424 INFO 18796 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-04-28 11:11:17.666 INFO 18796 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-04-28 11:11:17.682 INFO 18796 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
2022-04-28 11:11:17.977 INFO 18796 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-04-28 11:11:18.038 INFO 18796 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.8.Final
2022-04-28 11:11:18.267 INFO 18796 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-04-28 11:11:18.461 INFO 18796 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2022-04-28 11:11:18.827 ERROR 18796 --- [ main] j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: [PersistenceUnit:
default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.List, at table: order,
for columns: [org.hibernate.mapping.Column(ordered_items)]
2022-04-28 11:11:18.828 WARN 18796 --- [ main] 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 javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.List, at table: order, for columns: [org.hibernate.mapping.Column(ordered_items)]
2022-04-28 11:11:18.828 INFO 18796 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2022-04-28 11:11:18.832 INFO 18796 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2022-04-28 11:11:18.834 INFO 18796 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-04-28 11:11:18.859 INFO 18796 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-04-28 11:11:18.897 ERROR 18796 --- [ main] 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 javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.List, at table: order, for columns: [org.hibernate.mapping.Column(ordered_items)]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.7.jar:2.6.7]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.7.jar:2.6.7]
at com.springboot.fooddelivery.FoodDeliveryApplication.main(FoodDeliveryApplication.java:10) ~[classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.List, at table: order, for columns: [org.hibernate.mapping.Column(ordered_items)]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:421) ~[spring-orm-5.3.19.jar:5.3.19]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.19.jar:5.3.19]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.19.jar:5.3.19]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.19.jar:5.3.19]
... 16 common frames omitted
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.List, at table: order, for columns: [org.hibernate.mapping.Column(ordered_items)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:515) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:482) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.mapping.Property.isValid(Property.java:231) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:627) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.mapping.RootClass.validate(RootClass.java:267) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:359) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:314) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.19.jar:5.3.19]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.19.jar:5.3.19]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.19.jar:5.3.19]
... 20 common frames omitted
These are the 2 Entities I created
Dish.java
package com.springboot.fooddelivery.Models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Dish {
#Id
#GeneratedValue
private int DishId;
private String DishName;
private String DishCategory;
private double DishPrice;
private String DishDesc;
public Dish() {
super();
}
public Dish(int DishId, String DishName, String DishCategory, double DishPrice, String DishDesc) {
this.DishId = DishId;
this.DishName = DishName;
this.DishCategory = DishCategory;
this.DishPrice = DishPrice;
this.DishDesc = DishDesc;
}
public int getDishId() {
return DishId;
}
public void setDishId(int DishId) {
this.DishId = DishId;
}
public String getDishName() {
return DishName;
}
public void setDishName(String DishName) {
this.DishName = DishName;
}
public String getDishCategory() {
return DishCategory;
}
public void setDishCategory(String DishCategory) {
this.DishCategory = DishCategory;
}
public double getDishPrice() {
return DishPrice;
}
public void setDishPrice(double DishPrice) {
this.DishPrice = DishPrice;
}
public String getDishDesc() {
return DishDesc;
}
public void setDishDesc(String DishDesc) {
this.DishDesc = DishDesc;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + DishId;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Dish other = (Dish) obj;
if (DishId != other.DishId) {
return false;
}
return true;
}
#Override
public String toString() {
return String.format("Dish[DishId=%s, DishName=%s, DishCategory=%s, DishPrice=%s, DishDesc=%s]",
DishId, DishName, DishCategory, DishPrice, DishDesc);
}
}
Order.java
package com.springboot.fooddelivery.Models;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Order {
#Id
#GeneratedValue
private int orderId;
private List<Dish> orderedItems;
private float orderTotal;
private String deliveryAddress;
public Order() {
super();
}
public Order(int orderId, List<Dish> orderedItems, float orderTotal, String deliveryAddress) {
this.orderId = orderId;
this.orderedItems = orderedItems;
this.orderTotal = orderTotal;
this.deliveryAddress = deliveryAddress;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public List<Dish> getOrderedItems() {
return orderedItems;
}
public void setOrderedItems(List<Dish> orderedItems) {
this.orderedItems = orderedItems;
}
public float getOrderTotal() {
return orderTotal;
}
public void setOrderTotal(float orderTotal) {
this.orderTotal = orderTotal;
}
public String getDeliveryAddress() {
return deliveryAddress;
}
public void setDeliveryAddress(String deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
#Override
public int hashCode() {
final int prime = 43;
int result = 1;
result = prime * result + orderId;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Order other = (Order) obj;
if (orderId != other.orderId) {
return false;
}
return true;
}
}
This is my application.properties file
spring.datasource.url=jdbc:h2:mem:testdb
spring.data.jpa.repositories.bootstrap-mode=default
spring.h2.console.enabled=true
spring.jpa.show-sql=true
logging.level.org.springframework.web=INFO
This is my pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 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.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>food-delivery</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>food-delivery</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>18</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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
You should resolve below two issues
1. private List<Dish> orderedItems is not mapped
From yous log it's clear org.hibernate.MappingException: Could not determine type for: java.util.List.
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Dish> orderedItems = new ArrayList<>();
More Info - https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/
2. You are using order as your entity name, actually, the order is a SQL reserved word
#Entity(name = "MyOrder")
public class Order {
//TODO
}
More Info - https://www.drupal.org/docs/develop/coding-standards/list-of-sql-reserved-words
and JPA/Hibernate can't create Entity called Order
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'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.
I'm currently developing crud web-application with spingboot and hibernate, and experiencing difficulties with displaying pages in browser (returns "page not found" 404 error and no mapping warning in Spring log). For some reason I also cannot preview jsp-pages as Idea states that "There is no configured/running web-servers found!" even tough spring-web has embedded Tomcat server.
Webconfig:
package testgroup.private_clinic.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages ="testgroup.private_clinic")
public class Webconfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/res/**").addResourceLocations("/res/");
}
#Bean
ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setSuffix(".jsp");
viewResolver.setPrefix("/WEB-INF/pages/");
return viewResolver;
}
}
AppInitializer:
package testgroup.private_clinic.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{HibernateConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{Webconfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[] {characterEncodingFilter};
}
}
Controller:
package testgroup.private_clinic.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import testgroup.private_clinic.model.Patient;
import testgroup.private_clinic.service.PatientService;
import java.util.List;
#Controller
public class PatientController {
PatientService patientService;
#Autowired
public void setPatienceService(PatientService patientService){
this.patientService = patientService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView allPatients(){
List<Patient> patients = patientService.allPatients();
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("patients");
modelAndView.addObject("patientList", patients);
return modelAndView;
}
#RequestMapping(value= "/edit{id}", method = RequestMethod.GET)
public ModelAndView editPage(#PathVariable("id") int id){
Patient patient = patientService.getByID(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("editPage");
modelAndView.addObject("patient", patient);
return modelAndView;
}
#RequestMapping(value="/edit", method = RequestMethod.POST)
public ModelAndView editPatient(#ModelAttribute("patient") Patient patient){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("redirect:/");
patientService.edit(patient);
return modelAndView;
}
}
Pom-file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>testorg</groupId>
<artifactId>private_clinic</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.28.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
Spring log:
2021-03-06 02:46:33.941 INFO 13956 --- [ main] t.private_clinic.SpringBootClass : Starting SpringBootClass on DESKTOP-96Q7T8E with PID 13956 (C:\Users\Anton\IdeaProjects\Private_clinic_temp\target\classes started by Anton in C:\Users\Anton\IdeaProjects\Private_clinic_temp)
2021-03-06 02:46:33.943 INFO 13956 --- [ main] t.private_clinic.SpringBootClass : No active profile set, falling back to default profiles: default
2021-03-06 02:46:34.712 INFO 13956 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-03-06 02:46:34.719 INFO 13956 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-03-06 02:46:34.719 INFO 13956 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.43]
2021-03-06 02:46:34.793 INFO 13956 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-03-06 02:46:34.793 INFO 13956 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 820 ms
2021-03-06 02:46:34.900 INFO 13956 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.28.Final
2021-03-06 02:46:34.995 INFO 13956 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-03-06 02:46:35.107 INFO 13956 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
2021-03-06 02:46:35.506 INFO 13956 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-03-06 02:46:35.748 INFO 13956 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-03-06 02:46:35.756 INFO 13956 --- [ main] t.private_clinic.SpringBootClass : Started SpringBootClass in 2.044 seconds (JVM running for 2.527)
2021-03-06 02:46:48.864 INFO 13956 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-03-06 02:46:48.864 INFO 13956 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-03-06 02:46:48.868 INFO 13956 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
Hibernate: select patient0_.id as id1_0_0_, patient0_.adress as adress2_0_0_, patient0_.diagnosis as diagnosi3_0_0_, patient0_.patient_name as patient_4_0_0_, patient0_.patient_patronimic as patient_5_0_0_, patient0_.status as status6_0_0_, patient0_.patient_surname as patient_7_0_0_ from patients patient0_ where patient0_.id=?
2021-03-06 02:46:48.991 WARN 13956 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound : No mapping for GET /WEB-INF/pages/editPage.jsp
Main Class:
package testgroup.private_clinic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication(exclude = HibernateJpaAutoConfiguration.class)
public class SpringBootClass extends SpringBootServletInitializer {
public static void main(String[] args){
SpringApplication.run(SpringBootClass.class, args);
}
}
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.