Spring boot Auto-generated controllers - spring-boot

In the official Spring tutorial code source coode there are no controller required, so I didn't put them in my sample, however when I try to run my simple app I keep getting for http://localhost:8080/ or for http://localhost:8080/invoice the error:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing
this as a fallback. Thu Mar 09 10:18:51 CET 2017 There was an
unexpected error (type=Not Found, status=404). No message available
Structure:
$ tree
.
├── domain
│   ├── Invoice.java
│   └── InvoiceRepository.java
├── QbsApplication.java
invoice.java:
package qbs.domain;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
#Getter
#Setter
#ToString
public class Invoice {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String issuedBy;
protected Invoice() {
}
public Invoice(String issuedBy) {
this.issuedBy = issuedBy;
}
}
REPO:
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface InvoiceRepository extends PagingAndSortingRepository<Invoice, Long> {
List<Invoice> findByIssuedBy(#Param("issuer")String issuer);
}
and APP:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class QbsApplication {
public static void main(String[] args) {
SpringApplication.run(QbsApplication.class, args);
}
}
1. What seems to be the problem?
2. Can this be the lombok causing the issue (user the start.spring.io initializer though)?
EDIT
Spring BOot log:
2017-03-09 11:12:43.233 INFO 16837 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2017-03-09 11:12:43.235 INFO 16837 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-03-09 11:12:43.236 INFO 16837 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-03-09 11:12:43.274 INFO 16837 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-03-09 11:12:43.370 INFO 16837 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2017-03-09 11:12:43.479 INFO 16837 --- [ main] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2017-03-09 11:12:43.481 INFO 16837 --- [ main] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#38ed139b
2017-03-09 11:12:43.695 WARN 16837 --- [ main] org.hibernate.orm.deprecation : HHH90000014: Found use of deprecated [org.hibernate.id.SequenceGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead. See Hibernate Domain Model Mapping Guide for details.
2017-03-09 11:12:43.949 INFO 16837 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-03-09 11:12:44.464 INFO 16837 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#6385cb26: startup date [Thu Mar 09 11:12:40 CET 2017]; root of context hierarchy
2017-03-09 11:12:44.546 INFO 16837 --- [ 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-03-09 11:12:44.547 INFO 16837 --- [ 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-03-09 11:12:44.576 INFO 16837 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-09 11:12:44.576 INFO 16837 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-09 11:12:44.614 INFO 16837 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-03-09 11:12:44.923 INFO 16837 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-03-09 11:12:44.988 INFO 16837 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-03-09 11:12:44.994 INFO 16837 --- [ main] qbs.QbsApplication : Started QbsApplication in 4.875 seconds (JVM running for 5.356)

You forgot to annotate your repository with #RepositoryRestResource. If you don't, Spring will not auto generate the url mappings and it will just act as a normal repository. This is a feature of spring-data-rest. So, in your case:
#RepositoryRestResource(collectionResourceRel = "invoices", path = "invoices")
public interface InvoiceRepository extends PagingAndSortingRepository<Invoice, Long> {
List<Invoice> findByIssuedBy(#Param("issuer")String issuer);
}
Now curl http://localhost:8080/invoices will return all invoices.
Refer to the Spring Data Rest documentation for more info.

Related

POST request 404 not found

Hello fellow programmers, I'm having trouble solving the 404 error in postman when I request the POST method.
{
"timestamp": "2022-06-01T03:17:33.459+00:00",
"status": 404,
"error": "Not Found",
"path": "/parking-spot"
}
I'm creating an API that does the parking control with Spring Boot. The program does not show any errors when I run the application.
2022-06-01 00:37:35.226 INFO 1720 --- [ main] c.a.p.ParkingControlApplication : Starting ParkingControlApplication using Java 17.0.2 on DESKTOP-7GPB86C with PID 1720 (C:\Users\sergio\Documents\Projetos\Spring boot\Projeto 01\parking-control\Parking Control\target\classes started by sergio in C:\Users\sergio\Documents\Projetos\Spring boot\Projeto 01\parking-control\Parking Control)
2022-06-01 00:37:35.228 INFO 1720 --- [ main] c.a.p.ParkingControlApplication : No active profile set, falling back to 1 default profile: "default"
2022-06-01 00:37:35.558 INFO 1720 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-06-01 00:37:35.568 INFO 1720 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 3 ms. Found 0 JPA repository interfaces.
2022-06-01 00:37:36.078 INFO 1720 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-06-01 00:37:36.091 INFO 1720 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-06-01 00:37:36.092 INFO 1720 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-06-01 00:37:36.177 INFO 1720 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-06-01 00:37:36.177 INFO 1720 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 908 ms
2022-06-01 00:37:36.275 INFO 1720 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-06-01 00:37:36.307 INFO 1720 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.9.Final
2022-06-01 00:37:36.421 INFO 1720 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-06-01 00:37:36.493 INFO 1720 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-06-01 00:37:36.634 INFO 1720 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-06-01 00:37:36.654 INFO 1720 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
2022-06-01 00:37:36.821 INFO 1720 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-06-01 00:37:36.829 INFO 1720 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-06-01 00:37:36.864 WARN 1720 --- [ 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-06-01 00:37:37.106 INFO 1720 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-06-01 00:37:37.113 INFO 1720 --- [ main] c.a.p.ParkingControlApplication : Started ParkingControlApplication in 2.176 seconds (JVM running for 2.494)
2022-06-01 00:38:30.217 INFO 1720 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-06-01 00:38:30.217 INFO 1720 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-06-01 00:38:30.218 INFO 1720 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Aplication:
package com.api.parkingcontrol;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#SpringBootApplication
#RestController
#ComponentScan("ParkingSpotController")
#EnableJpaRepositories("ParkingSpotRepository")
#EntityScan("ParkingSpotRepository")
public class ParkingControlApplication {
public static void main(String[] args) {
SpringApplication.run(ParkingControlApplication.class, args);
}
#GetMapping("/")
public String index() {
return "Olá Mundo";
}
}
Controller:
package com.api.parkingcontrol.controllers;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.api.parkingcontrol.dtos.ParkingSpotDto;
import com.api.parkingcontrol.models.ParkingSpotModel;
import com.api.parkingcontrol.services.ParkingSpotService;
#RestController
#CrossOrigin(origins = "*", maxAge = 3600)
#RequestMapping(value = "/parking-spot")
public class ParkingSpotController {
final ParkingSpotService parkingSpotService;
public ParkingSpotController(ParkingSpotService parkingSpotService) {
this.parkingSpotService = parkingSpotService;
}
#PostMapping("/parking-spot")
#ResponseBody
public ResponseEntity<Object> saveParkingSpot(#RequestBody #Valid ParkingSpotDto parkingSpotDto) {
if (parkingSpotService.existByLicensePlateCar(parkingSpotDto.getLicensePlateCar())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("Conflict: License Plate Car is already in use!");
}
if (parkingSpotService.existsByParkingSpotNumber(parkingSpotDto.getParkingSpotNumber())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("Conflict: Parking Spot already in use!");
}
if (parkingSpotService.existsByApartmentAndBlock(parkingSpotDto.getApartament(), parkingSpotDto.getBlock())) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body("Conflict: Parking Spot already registered for this apartment/block!");
}
var parkingSpotModel = new ParkingSpotModel();
BeanUtils.copyProperties(parkingSpotDto, parkingSpotModel);
parkingSpotModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
return ResponseEntity.status(HttpStatus.CREATED).body(parkingSpotService.save(parkingSpotModel));
}
#GetMapping
public ResponseEntity<List<ParkingSpotModel>> getAllParkingSpots() {
return ResponseEntity.status(HttpStatus.OK).body(parkingSpotService.findAll());
}
}
Service:
package com.api.parkingcontrol.services;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.api.parkingcontrol.models.ParkingSpotModel;
import com.api.parkingcontrol.repositories.ParkingSpotRepository;
#Service
public class ParkingSpotService {
final ParkingSpotRepository parkingSpotRepository;
/*Constructor do Repository*/
public ParkingSpotService(ParkingSpotRepository parkingSpotRepository) {
this.parkingSpotRepository = parkingSpotRepository;
}
#Transactional
public Object save(ParkingSpotModel parkingSpotModel) {
return parkingSpotRepository.save(parkingSpotModel);
}
public boolean existByLicensePlateCar(String licensePlateCar) {
return parkingSpotRepository.existByLicensePlateCar(licensePlateCar);
}
public boolean existsByParkingSpotNumber(String parkingSpotNumber) {
return parkingSpotRepository.existsByParkingSpotNumber(parkingSpotNumber);
}
public boolean existsByApartmentAndBlock(String apartament, String block) {
return parkingSpotRepository.existsByApartmentAndBlock(apartament, block);
}
public List<ParkingSpotModel> findAll (){
return parkingSpotRepository.findAll();
}
}
Am I missing something?
The problem is that in your controller you have
1)
#RequestMapping(value = "/parking-spot")
public class ParkingSpotController
and
2)
#PostMapping("/parking-spot")
#ResponseBody
public ResponseEntity<Object> saveParkingSpot
This means that your endpoint will be available by the path: /parking-spot/parking-spot

Illegal use of #Table in a subclass of a SINGLE_TABLE hierarchy

I'm a newbie in Spring. I try to create a project with SOLID techniques but was faced with that error. Inheritance does not work in my application. Why inheritance does not work properly? Is inheritance allowed in Spring?
Text of Error:
2021-06-23 23:54:08.928 INFO 12984 --- [ restartedMain] hrms.northwind.NorthwindApplication : Starting NorthwindApplication using Java 15.0.2 on DESKTOP-87K40S0 with PID 12984 (C:\Users\90553\Desktop\Eclipse Projects\HRMS Project\target\classes started by 90553 in C:\Users\90553\Desktop\Eclipse Projects\HRMS Project)
2021-06-23 23:54:08.929 INFO 12984 --- [ restartedMain] hrms.northwind.NorthwindApplication : No active profile set, falling back to default profiles: default
2021-06-23 23:54:08.978 INFO 12984 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-06-23 23:54:08.978 INFO 12984 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-06-23 23:54:09.465 INFO 12984 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-06-23 23:54:09.512 INFO 12984 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 40 ms. Found 2 JPA repository interfaces.
2021-06-23 23:54:10.040 INFO 12984 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-06-23 23:54:10.052 INFO 12984 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-06-23 23:54:10.052 INFO 12984 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.46]
2021-06-23 23:54:10.130 INFO 12984 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-06-23 23:54:10.130 INFO 12984 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1152 ms
2021-06-23 23:54:10.203 INFO 12984 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-06-23 23:54:10.367 INFO 12984 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-06-23 23:54:10.458 INFO 12984 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-06-23 23:54:10.502 INFO 12984 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-06-23 23:54:10.619 INFO 12984 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-06-23 23:54:10.721 INFO 12984 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2021-06-23 23:54:11.047 WARN 12984 --- [ restartedMain] org.hibernate.cfg.AnnotationBinder : HHH000139: Illegal use of #Table in a subclass of a SINGLE_TABLE hierarchy: hrms.northwind.entities.concretes.Employer
2021-06-23 23:54:11.049 WARN 12984 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.ClassCastException: class org.hibernate.mapping.SingleTableSubclass cannot be cast to class org.hibernate.mapping.RootClass (org.hibernate.mapping.SingleTableSubclass and org.hibernate.mapping.RootClass are in unnamed module of loader 'app')
2021-06-23 23:54:11.050 INFO 12984 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-06-23 23:54:11.053 INFO 12984 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2021-06-23 23:54:11.057 INFO 12984 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-06-23 23:54:11.066 INFO 12984 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-06-23 23:54:11.084 ERROR 12984 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
Employer Class:
package hrms.northwind.entities.concretes;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
#Entity(name="Employers")
#Table(name="Employers")
#Data
public class Employer extends Person {
#Id
#GeneratedValue
#Column(name="employer_id")
private int employerId;
#Column(name="company_name")
private String company_name;
#Column(name="website")
private String website;
#Column(name="phone_number")
private String phone_number;
#Column(name="password")
private String password;
public Employer(int personId, String name, String surname, String email, int employerId, String company_name, String website,
String phone_number, String password) {
super(personId, name, surname, email);
this.employerId = employerId;
this.company_name = company_name;
this.website = website;
this.phone_number = phone_number;
this.password = password;
}
}
Employer Dao:
package hrms.northwind.dataAccess.abstracts;
import org.springframework.data.jpa.repository.JpaRepository;
import hrms.northwind.entities.concretes.Employer;
public interface EmployerDao extends JpaRepository<Employer,Integer>{
}
Employer Service:
package hrms.northwind.business.abstracts;
import java.util.List;
import org.springframework.stereotype.Service;
import hrms.northwind.entities.concretes.Employer;
#Service
public interface EmployerService {
List<Employer> getAll();
}
Employer Controller:
package hrms.northwind.api.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import hrms.northwind.business.abstracts.EmployerService;
import hrms.northwind.entities.concretes.Employer;
#RestController
#RequestMapping("/api/employers")
public class EmployerController {
private EmployerService employerService;
#Autowired
public EmployerController(EmployerService employerService) {
super();
this.employerService = employerService;
}
#GetMapping("/getall")
public List<Employer> getAll(){
return this.employerService.getAll();
}
}
Employer Table:
Employer Table
Any help?
Maybe is late for this answer
I think the problem comes from #Table. That annotation is optional when you want to specify an entity.
You could find better documented answer here
You can add this to your Employer class.
#Inheritance(strategy = InheritanceType.JOINED)
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#PrimaryKeyJoinColumn(name="employer_id",referencedColumnName = "person_id")

Using different packages for Controllers when using in Spring Boot

I am new in Spring boot.I trying to access the controller url but i didn't get any response from them.
We are followed spring boot project structure as per document.
I have used componentscan annotation and added scanBasePackageClasses in SpringBootApplication annotation.But still same.
HomeController :-
package com.main.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#RequestMapping(value="/home",method=RequestMethod.GET)
public String home() {
System.out.println("home");
return "home";
}
}
GAppsApplication.java:-
package com.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.main.controllers.HomeController;
#ComponentScan({"com.main.controllers"})
#SpringBootApplication(scanBasePackageClasses={HomeController.class})
public class GAppsApplication {
public static void main(String[] args) {
SpringApplication.run(GAppsApplication.class, args);
}
}
For your reference i shared below logs
logs:-
2018-08-28 08:26:16.404 INFO 8172 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#58b9d6, org.springframework.security.web.context.SecurityContextPersistenceFilter#525747, org.springframework.security.web.header.HeaderWriterFilter#1638752, org.springframework.security.web.csrf.CsrfFilter#324c61, org.springframework.security.web.authentication.logout.LogoutFilter#14a6743, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#12d6ce4, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#1837d01, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#eda2d2, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#4a5109, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#4bb38c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#12205be, org.springframework.security.web.session.SessionManagementFilter#2e4343, org.springframework.security.web.access.ExceptionTranslationFilter#1a81a58, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#12e7437]
2018-08-28 08:26:16.558 INFO 8172 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-08-28 08:26:16.592 INFO 8172 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-08-28 08:26:16.594 INFO 8172 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-08-28 08:26:16.600 INFO 8172 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-08-28 08:26:16.638 INFO 8172 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-08-28 08:26:16.642 INFO 8172 --- [ restartedMain] c.main.GAppsApplication : Started GAppsApplication in 5.153 seconds (JVM running for 5.734)
2018-08-28 08:27:11.961 INFO 8172 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-08-28 08:27:11.961 INFO 8172 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-08-28 08:27:11.980 INFO 8172 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 19 ms
Change your controller to like below :
#RestController
#RequestMapping("/home")
public class HomeController {
#GetMapping
public String home() {
System.out.println("home");
return "home";
}
}
As your base package is com.main, so any package within com.main will automatically be scanned.
You don't need to put any special annotation to scan.

Spring boot unit test not picking up request mapping for mocked controller

I am trying to test my Controller but the console says the url mapping are not found for the mocked request, i can see the dynamic mapping coming up in the console after i fire my tests & they are getting mapped to the respective methods.
In my setup i have a mocked service which is getting injected inside controller i want to test.
Here is the test webapp configuration
package com.example.persistance;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.example.dao.UserDao;
import com.example.model.User;
#Configuration
#ComponentScan("com.example")
#EnableWebMvc
class MockWebConfigurationForTest{
#Bean
public UserDao setupMockUserDao() {
User mockUser;
mockUser=new User();
mockUser.setId(TestCaseConstants.UserId.uuidAsString());
mockUser.setAge("24");
mockUser.setFirstName("Sujal");
mockUser.setLastName("Mandal");
mockUser.setUserName("smandal");
mockUser.setPasswordHash("ABCDE12345");
UserDao userDao=mock(UserDao.class);
when(userDao.findOne(TestCaseConstants.UserId.uuidAsString())).thenReturn(mockUser);
return userDao;
}
}
Here is the test class
package com.example.persistance;
import static org.junit.Assert.assertNotNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.example.controllers.UserController;
import com.example.model.User;
import com.google.gson.Gson;
#RunWith(SpringRunner.class)
#SpringBootTest
#WebAppConfiguration
#ContextConfiguration(classes = {MockWebConfigurationForTest.class})
public class DataPersistenceServiceApplicationTests {
MockMvc mockMvc;
String mockUserId=TestCaseConstants.UserId.uuidAsString();
User mockUser;
#InjectMocks
private UserController userController;
#Before
public void setUpTestData() {
mockUser=new User();
mockUser.setId(mockUserId);
mockUser.setAge("24");
mockUser.setFirstName("Sujal");
mockUser.setLastName("Mandal");
mockUser.setUserName("smandal");
mockUser.setPasswordHash("ABCDE12345");
MockitoAnnotations.initMocks(this);
mockMvc=MockMvcBuilders.standaloneSetup(UserController.class).build();
}
#Test
public void testUserController_getOne() throws Exception {
String result=mockMvc.perform(get("/info")).andReturn().getResponse().getContentAsString();
assertNotNull(result);
}
}
When i run the test, i see the followings in the console.
2018-02-14 11:31:39.912 INFO 9408 --- [ main] p.DataPersistenceServiceApplicationTests : No active profile set, falling back to default profiles: default
2018-02-14 11:31:39.915 INFO 9408 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Refreshing org.springframework.web.context.support.GenericWebApplicationContext#427b5f92: startup date [Wed Feb 14 11:31:39 IST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#1b2abca6
2018-02-14 11:31:40.946 INFO 9408 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=9c2829f3-6e5c-30f7-aeae-06169329e061
2018-02-14 11:31:41.023 INFO 9408 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-02-14 11:31:41.138 INFO 9408 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$4404e8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-02-14 11:31:41.822 INFO 9408 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-02-14 11:31:41.892 INFO 9408 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:40}] to localhost:27017
2018-02-14 11:31:41.894 INFO 9408 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 2]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, roundTripTimeNanos=597711}
2018-02-14 11:31:42.279 INFO 9408 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/info]}" onto public java.lang.String com.example.controllers.InfoController.info()
2018-02-14 11:31:42.282 INFO 9408 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/],methods=[GET]}" onto public java.util.List<com.example.model.User> com.example.controllers.UserController.getAllUsers()
2018-02-14 11:31:42.282 INFO 9408 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/],methods=[PUT]}" onto public com.example.model.User com.example.controllers.UserController.updateOne(com.example.model.User)
2018-02-14 11:31:42.282 INFO 9408 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/],methods=[DELETE]}" onto public void com.example.controllers.UserController.deleteOne(com.example.model.User)
2018-02-14 11:31:42.283 INFO 9408 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/],methods=[POST]}" onto public com.example.model.User com.example.controllers.UserController.saveOne(com.example.model.User)
2018-02-14 11:31:42.283 INFO 9408 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users/{id}],methods=[GET]}" onto public com.example.model.User com.example.controllers.UserController.getOne(java.lang.String)
2018-02-14 11:31:42.287 INFO 9408 --- [ 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)
2018-02-14 11:31:42.288 INFO 9408 --- [ 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)
2018-02-14 11:31:42.605 INFO 9408 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext#427b5f92: startup date [Wed Feb 14 11:31:39 IST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#1b2abca6
2018-02-14 11:31:43.231 WARN 9408 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2018-02-14 11:31:43.231 INFO 9408 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2018-02-14 11:31:43.241 WARN 9408 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2018-02-14 11:31:43.241 INFO 9408 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2018-02-14 11:31:44.386 WARN 9408 --- [ main] arterDeprecationWarningAutoConfiguration : spring-cloud-starter-eureka is deprecated as of Spring Cloud Netflix 1.4.0, please migrate to spring-cloud-starter-netflix-eureka
2018-02-14 11:31:44.458 INFO 9408 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2018-02-14 11:31:44.471 INFO 9408 --- [ main] p.DataPersistenceServiceApplicationTests : Started DataPersistenceServiceApplicationTests in 6.268 seconds (JVM running for 7.277)
2018-02-14 11:31:44.674 INFO 9408 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext#5ec9eefa
2018-02-14 11:31:44.695 INFO 9408 --- [ main] o.s.mock.web.MockServletContext : Initializing Spring FrameworkServlet ''
2018-02-14 11:31:44.700 INFO 9408 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization started
2018-02-14 11:31:44.701 INFO 9408 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization completed in 0 ms
==> 2018-02-14 11:31:44.779 WARN 9408 --- [ main] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/info] in DispatcherServlet with name
2018-02-14 11:31:44.807 INFO 9408 --- [ Thread-5] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#427b5f92: startup date [Wed Feb 14 11:31:39 IST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#1b2abca6
As the 2nd last line says the mapping for /info is not found but if you see a little bit above you can see the mappings are picked up successfully, what am i missing ?
I found the solution, i used mockMvc=MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
instead of standaloneSetup() I used an Autowired instance of webApplicationContext
package com.example.persistance;
import static org.junit.Assert.assertNotNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.example.controllers.UserController;
import com.example.model.User;
import com.google.gson.Gson;
#RunWith(SpringRunner.class)
#SpringBootTest
#ContextConfiguration(classes = {MockWebConfigurationForTest.class})
public class DataPersistenceServiceApplicationTests {
#Autowired
WebApplicationContext webApplicationContext;
MockMvc mockMvc;
String mockUserId=TestCaseConstants.UserId.uuidAsString();
User mockUser;
#InjectMocks
private UserController userController;
#Before
public void setUpTestData() {
mockUser=new User();
mockUser.setId(mockUserId);
mockUser.setAge("24");
mockUser.setFirstName("Sujal");
mockUser.setLastName("Mandal");
mockUser.setUserName("smandal");
mockUser.setPasswordHash("ABCDE12345");
MockitoAnnotations.initMocks(this);
mockMvc=MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#Test
public void testUserController_getOne() throws Exception {
Gson gson=new Gson();
System.err.println("Expected: "+gson.toJson(mockUser));
String result=mockMvc.perform(get("/users/"+mockUserId)).andReturn().getResponse().getContentAsString();
System.err.println("Returned: "+result);
assertNotNull(result);
}
}

Tables can't be generated using spring boot

I don't have any error but i can not generate the database ,here's what i have in console :
2015-05-14 16:23:23.655 INFO 4580 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {4.3.8.Final}
2015-05-14 16:23:23.663 INFO 4580 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2015-05-14 16:23:23.670 INFO 4580 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2015-05-14 16:23:24.218 INFO 4580 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2015-05-14 16:23:25.307 INFO 4580 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2015-05-14 16:23:25.466 INFO 4580 --- [ main] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2015-05-14 16:23:25.817 INFO 4580 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2015-05-14 16:23:25.825 INFO 4580 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2015-05-14 16:23:26.508 INFO 4580 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#20d04b: startup date [Thu May 14 16:23:13 CEST 2015]; root of context hierarchy
2015-05-14 16:23:26.790 INFO 4580 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" 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)
2015-05-14 16:23:26.791 INFO 4580 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2015-05-14 16:23:26.878 INFO 4580 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-05-14 16:23:26.878 INFO 4580 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-05-14 16:23:27.038 INFO 4580 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-05-14 16:23:27.617 INFO 4580 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2015-05-14 16:23:27.832 INFO 4580 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2015-05-14 16:23:27.837 INFO 4580 --- [ main] demo.DemoJpaTApplication : Started DemoJpaTApplication in 15.327 seconds (JVM running for 16.798)
Here's my 2 entities :database and Entities (i have many entities belong to one database)
package entities;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
#Entity
public class Database implements Serializable {
private int id_database;
private String database_name;
#OneToMany
#JoinColumn(name="id_entity")
private Collection <Entities> entities;
public int getId_database() {
return id_database;
}
public void setId_database(int id_database) {
this.id_database = id_database;
}
public String getDatabase_name() {
return database_name;
}
public void setDatabase_name(String database_name) {
this.database_name = database_name;
}
public Database() {
super();
// TODO Auto-generated constructor stub
}
public Database(int id_database, String database_name) {
super();
this.id_database = id_database;
this.database_name = database_name;
}
#Override
public String toString() {
return "Database [id_database=" + id_database + ", database_name="
+ database_name + "]";
}
}
package entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Entities implements Serializable {
private int id_entity;
private String entity_name;
#ManyToOne
#JoinColumn(name="id_database")
private Database d;
public int getId_entity() {
return id_entity;
}
public void setId_entity(int id_entity) {
this.id_entity = id_entity;
}
public String getEntity_name() {
return entity_name;
}
public void setEntity_name(String entity_name) {
this.entity_name = entity_name;
}
}
Here's my application.properties where i mentioned the connection and its details ,the driver ....,i am following the offical documentation of spring boot
# DataSourcesettings:
spring.datasource.url= jdbc:mysql://localhost:3306/db_hajar
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driverClassName= com.mysql.jdbc.Driver
# Specifythe DBMS
spring.jpa.database = MYSQL
# Show or not log for each sqlquery
spring.jpa.show-sql = true
# Hibernateddlauto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto =update
# Namingstrategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
# ViewResolver
spring.view.prefix: /WEB-INF/views/
spring.view.suffix: .jsp
Have you tried to set ddl-auto property to create or create-drop?
spring.jpa.hibernate.ddl-auto = create

Resources