Unknown column in 'field list' in cascading persistance - spring-boot

I am using Spring Boot Version 2.5.2 , spring data jpa and MySQL Database
CREATE TABLE Timesheet (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`tsYear` VARCHAR(4) NOT NULL,
`weekNumber` INT NOT NULL,
`startDate` DATE NOT NULL,
`endDate` DATE NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE TimesheetDays (
`id` INT NOT NULL AUTO_INCREMENT,
`timesheetId` BIGINT(20) NOT NULL,
`dayNumber` INT NOT NULL,
`dayDate` DATE NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `tsdTimesheetId`
FOREIGN KEY (`timesheetId`)
REFERENCES Timesheet (`id`)
);
#Entity
#Table(name = "timesheet")
public class Timesheet {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "timesheet")
private List<TimesheetDay> days = null;
}
#Entity
#Table(name = "timesheetdays")
public class TimesheetDay {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne
private Timesheet timesheet;
}
When i tried to save (timesheet and timesheetdays), for timesheetdays table, hibernate is
generating wrong column.
[2m2021-11-05 18:29:44.147[0;39m [32mDEBUG[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36morg.hibernate.SQL [0;39m [2m:[0;39m insert into timesheetdays (daydate, daynumber, timesheet_id) values (?, ?, ?)
[2m2021-11-05 18:29:44.147[0;39m [32mTRACE[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.h.type.descriptor.sql.BasicBinder [0;39m [2m:[0;39m binding parameter [1] as [DATE] - [2017-12-20]
[2m2021-11-05 18:29:44.148[0;39m [32mTRACE[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.h.type.descriptor.sql.BasicBinder [0;39m [2m:[0;39m binding parameter [2] as [INTEGER] - [1]
[2m2021-11-05 18:29:44.148[0;39m [32mTRACE[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.h.type.descriptor.sql.BasicBinder [0;39m [2m:[0;39m binding parameter [3] as [INTEGER] - [18]
[2m2021-11-05 18:29:44.148[0;39m [33m WARN[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.h.engine.jdbc.spi.SqlExceptionHelper [0;39m [2m:[0;39m SQL Error: 1054, SQLState: 42S22
[2m2021-11-05 18:29:44.148[0;39m [31mERROR[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.h.engine.jdbc.spi.SqlExceptionHelper [0;39m [2m:[0;39m Unknown column 'timesheet_id' in 'field list'
Since the generated column name is timesheet_id, it is not working.
If the generated column name becomes timesheetid, it will work.
Please help to resolve this issue

You need to add the #JoinColumn annotation to give the column name value specifically in your TimesheetDay entity.
#ManyToOne
#JoinColumn(name="timesheetid")
private Timesheet timesheet;

Related

No mapping for DELETE

this is the implementation if the Http Delete method where i'm trying to delete this object
"vente" by it's id, and as seen below the mapping is provided for the DELETE method.
#DeleteMapping(value = ConstantController.VENTE+"/{venteId}")
public ResponseEntity<?> deleteVente(#PathVariable BigInteger venteId){
venteService.deleteVente(venteId);
return new ResponseEntity<Void>(HttpStatus.OK);
}
this is the uri for accessing the the service:
http://localhost:8080/stock-ws/vente/1
this what i get in the server tomcat log when i send the http request with the delete
method:
2021-10-17 22:18:29.258[0;39m [32m INFO[0;39m [35m3848[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/] [0;39m [2m:[0;39m Initializing Spring DispatcherServlet 'dispatcherServlet'
[2m2021-10-17 22:18:29.258[0;39m [32m INFO[0;39m [35m3848[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Initializing Servlet 'dispatcherServlet'
[2m2021-10-17 22:18:29.262[0;39m [32m INFO[0;39m [35m3848[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Completed initialization in 4 ms
[2m2021-10-17 22:18:29.289[0;39m [33m WARN[0;39m [35m3848[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.PageNotFound [0;39m [2m:[0;39m No mapping for DELETE /stock-ws/vente/1
couldn't spot the bug any help will be apreciated!
Maybe you can try this;
#RestController
#RequestMapping("/stock-ws/vente")
class TestController(){
#DeleteMapping("{venteId}")
public ResponseEntity<?> deleteVente(#PathVariable BigInteger venteId){
venteService.deleteVente(venteId);
return new ResponseEntity<Void>(HttpStatus.OK);
}
}

Spring Data JPA - one to one mapping bidirectional

I have a table called symbols and symbol history,
Symbols
symbols(Pk)
SymbolsHistorical
id
symbols
Forign key name - symbols_fk (FK)
I created my HibernateMapping and in my DTO classes,
In SymbolsHistorical,
#OneToOne
#JoinColumn(foreignKey = #ForeignKey(name = "symbols_fk"))
private Symbols symbol;
I did in Symbols class,
#OneToOne(mappedBy = "symbol")
private SymbolsHistorical symbolsHistorical;
Whenever I need to read symbols, I need its symbolsHistorical as well,
Iam using findBySymbol method to get symbolsData. Whenever I do the above mapping, am getting,
Unknown column 'symbols0_.symbols_historical_id' in 'field list'
What am doing wrong?
Update:
Error
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755)
[2m2021-07-05 15:31:29.458[0;39m [31mERROR[0;39m [35m76390[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36ms.e.ErrorMvcAutoConfiguration$StaticView[0;39m [2m:[0;39m Cannot render error page for request [/symbols/A] and exception [] as the response has already been committed. As a result, the response may have the wrong status code.
Taken from your tables the foreign key name is symbols.
So the mapping must be in Symbols class:
#OneToOne
#JoinColumn(name="symbols")
private Symbols symbol;
As you are using JSON serialization you will get a StackOverflowError because of the bi-directional mapping.
So you have to add an annotation to the Symbol or SymbolsHistorical class (depending on what you want to serialize) to break the loop.
For example
#JsonBackReference // this property will not be serialized
#OneToOne(mappedBy = "symbol")
private SymbolsHistorical symbolsHistorical;

Spring Security OAuth2 always redirects to /login page having a valid Bearer header

I am having a hard time getting Spring Security OAuth2 to work. I am able to get a access_token from /oauth/token endpoint but accessing a protected resource with that token in header "Authorization: Bearer $TOKEN" always redirects me to /login. This is a complete REST API.
OAuth2Config
#Configuration
public class OAuth2Configuration {
private static final String SERVER_RESOURCE_ID = "oauth2-server";
private static InMemoryTokenStore tokenStore = new InMemoryTokenStore();
#Configuration
#EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore).resourceId(SERVER_RESOURCE_ID);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/admin**").and().authorizeRequests().antMatchers("/admin**").access("#oauth2.hasScope('read')");
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore).approvalStoreDisabled();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("my-client")
.authorizedGrantTypes("authorization_code","refresh_token", "password")
.authorities("ROLE_CLIENT")
.scopes("read")
.resourceIds(SERVER_RESOURCE_ID)
.secret("secret")
;
}
}
}
SecurityConfig class
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder());
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
Following are the debug logs
2017-04-10 10:58:31.634[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Initializing servlet 'dispatcherServlet'
[2m2017-04-10 10:58:31.635[0;39m [32m INFO[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/] [0;39m [2m:[0;39m Initializing Spring FrameworkServlet 'dispatcherServlet'
[2m2017-04-10 10:58:31.635[0;39m [32m INFO[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m FrameworkServlet 'dispatcherServlet': initialization started
[2m2017-04-10 10:58:31.635[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Using MultipartResolver [org.springframework.web.multipart.support.StandardServletMultipartResolver#40aad17d]
[2m2017-04-10 10:58:31.639[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver#70f4e8c6]
[2m2017-04-10 10:58:31.643[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver#201a4016]
[2m2017-04-10 10:58:31.649[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#5f14eeee]
[2m2017-04-10 10:58:31.656[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager#1688575]
[2m2017-04-10 10:58:31.656[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Published WebApplicationContext of servlet 'dispatcherServlet' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet]
[2m2017-04-10 10:58:31.656[0;39m [32m INFO[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m FrameworkServlet 'dispatcherServlet': initialization completed in 21 ms
[2m2017-04-10 10:58:31.656[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Servlet 'dispatcherServlet' configured successfully
[2m2017-04-10 10:58:31.692[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m DispatcherServlet with name 'dispatcherServlet' processing POST request for [/oauth/token]
[2m2017-04-10 10:58:31.695[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m Looking up handler method for path /oauth/token
[2m2017-04-10 10:58:31.699[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m Did not find handler method for [/oauth/token]
[2m2017-04-10 10:58:32.012[0;39m [32m INFO[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.s.o.p.token.store.JdbcTokenStore [0;39m [2m:[0;39m Failed to find access token for token 7c74f287-e187-4228-b0c2-b79972f9b89b
[2m2017-04-10 10:58:32.226[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.w.s.m.m.a.HttpEntityMethodProcessor [0;39m [2m:[0;39m Written [7c74f287-e187-4228-b0c2-b79972f9b89b] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#2fd4312a]
[2m2017-04-10 10:58:32.226[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
[2m2017-04-10 10:58:32.226[0;39m [32mDEBUG[0;39m [35m6456[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Successfully completed request
What is it that I am missing? I have almost tried every example over the web into my existing project but I am always redirected to the /login endpoint when I try to request a protected resource with a valid token.
Thanks.
So it turned out that since I was upgrading from an earlier version of spring boot to 1.5.2, in the release notes it is said that the order of the resource filter has been changed. See here. Just place this magic property in application.properties file and it fixes everything.
security.oauth2.resource.filter-order = 3
he default order of the OAuth2 resource filter has changed from 3 to SecurityProperties.ACCESS_OVERRIDE_ORDER - 1. This places it after the actuator endpoints but before the basic authentication filter chain. The default can be restored by setting security.oauth2.resource.filter-order = 3.

Unable to load Jsp page using Spring Boot 1.4.3 Release Version and Spring 4.3.5.RELEASE version

I am new in the Spring Boot Application development.I am doing simple spring boot application using spring boot version 1.4.3 Release version and Spring 4.3.5.RELEASE version. I am successfully in the configuration of Mysql database configuration. Also table get created while running Spring Boot main class.
Below is Spring Boot project directory structure :
SpringBootApp[boot]
src/main/java
-config
-controller
-dto
-entity
-repository
-service
src/main/resources
-application.properties
src/test/java
src/main/webapp
/recources/css
/resources/images
/resources/js
/WEB-INF/view/jsp/main.jsp
I created DBConfig.java file which having DB related functionality like datasource creation,jpa transaction management.
Below is WebMVC configuration file:
#EnableWebMvc
#Configuration
#Import(DBConfig.class)
#ComponentScan(basePackages = { "com.tms" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Below is App Context initializer file :
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { DBConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
I also added below line of code in application.properties file to locate jsp pages and to deactivate thymeleaf template.
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
spring.thymeleaf.check-template-location=false
Below is Spring Controller java file:
#RequestMapping("/")
public class IndexController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("title", "Hello world!");
return "main";
}
}
Below jsp sample page :
/WEB-INF/jsp/main.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring Boot</title>
</head>
<body>
<h2>Test Page</h2>
<table>
<tr>
<td>Title</td>
<td>${title}</td>
</tr>
</table>
</body>
</html>
Spring Boot Application successfully get started.
Below is STS console output :
2017-01-12 04:22:57.501[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36morg.hibernate.tool.hbm2ddl.SchemaUpdate [0;39m [2m:[0;39m HHH000228: Running hbm2ddl schema update
[2m2017-01-12 04:22:57.677[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36mj.LocalContainerEntityManagerFactoryBean[0;39m [2m:[0;39m Initialized JPA EntityManagerFactory for persistence unit 'jpaUnit'
[2m2017-01-12 04:22:58.392[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m Mapped "{[/book]}" onto public org.springframework.http.ResponseEntity<java.util.List<com.tms.dto.BookDto>> com.tms.controller.BookController.getAllBooks()
[2m2017-01-12 04:22:58.400[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m 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)
[2m2017-01-12 04:22:58.401[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m 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)
[2m2017-01-12 04:22:58.466[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.s.w.s.handler.SimpleUrlHandlerMapping [0;39m [2m:[0;39m Mapped URL path [/resources/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[2m2017-01-12 04:22:58.476[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.s.w.s.handler.SimpleUrlHandlerMapping [0;39m [2m:[0;39m Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler]
[2m2017-01-12 04:22:58.596[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerAdapter[0;39m [2m:[0;39m Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#33d512c1: startup date [Thu Jan 12 04:22:49 IST 2017]; root of context hierarchy
[2m2017-01-12 04:23:00.111[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.s.j.e.a.AnnotationMBeanExporter [0;39m [2m:[0;39m Registering beans for JMX exposure on startup
[2m2017-01-12 04:23:00.265[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36ms.b.c.e.t.TomcatEmbeddedServletContainer[0;39m [2m:[0;39m Tomcat started on port(s): 8080 (http)
[2m2017-01-12 04:23:00.276[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[ main][0;39m [36mcom.tms.config.App [0;39m [2m:[0;39m Started App in 12.241 seconds (JVM running for 13.221)
[2m2017-01-12 04:23:01.999[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/] [0;39m [2m:[0;39m Initializing Spring FrameworkServlet 'dispatcherServlet'
[2m2017-01-12 04:23:02.000[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m FrameworkServlet 'dispatcherServlet': initialization started
[2m2017-01-12 04:23:02.040[0;39m [32m INFO[0;39m [35m4968[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m FrameworkServlet 'dispatcherServlet': initialization completed in 40 ms
When i type url http://localhost:8080/ in the browser it will give below message :
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Jan 12 04:24:27 IST 2017
There was an unexpected error (type=Not Found, status=404).
Also i tried http://localhost:8080/SpringBootApp/ url in the browserit will show below message :
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Jan 12 04:33:26 IST 2017
There was an unexpected error (type=Not Found, status=404).
/SpringBootApp/
No any error message printed in the STS console.
I would be thankful if anybody have solution/ to suggest other approach for the same.
Your views are in /view/jsp/, but your view resolver only says /view/. Also it seems wrong to have the configuration in both application.properties, and code.
And personally I would use Thymeleaf for server side rendering these days.
Change
viewResolver.setPrefix("/WEB-INF/view/");
to
viewResolver.setPrefix("/WEB-INF/view/jsp/");

Spring Boot Hibernate Syntax Error in SQL Statement

I've modified the Spring Boot JPA Data example (https://github.com/spring-guides/gs-accessing-data-jpa.git) slightly adding an Order entity and a corresponding one to many mapping to it from the customer. When I run the example there are several Syntax Error in SQL Statement lines logged by Hibernate. I'm trying to figure out why? I've pasted the code for the entities and the console output from the application below.
package hello;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
#OneToMany(mappedBy="customer")
private List<Order> orders;
protected Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
And a corresponding Order entity:
package hello;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
protected Order() {}
double amount;
#ManyToOne
Customer customer;
}
And the console output:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.1.10.RELEASE)
2015-01-16 08:56:53.116 INFO 27810 --- [ main] hello.Application : Starting Application on MKI with PID 27810 (/home/ole/Documents/workspace-sts-3.6.3.RELEASE/gs-accessing-data-jpa-complete/target/classes started by ole in /home/ole/Documents/workspace-sts-3.6.3.RELEASE/gs-accessing-data-jpa-complete)
2015-01-16 08:56:53.149 INFO 27810 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#5d59e6f1: startup date [Fri Jan 16 08:56:53 CST 2015]; root of context hierarchy
2015-01-16 08:56:54.253 INFO 27810 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2015-01-16 08:56:54.269 INFO 27810 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2015-01-16 08:56:54.320 INFO 27810 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {4.3.7.Final}
2015-01-16 08:56:54.322 INFO 27810 --- [ main] org.hibernate.cfg.Environment : HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.charSet=UTF-8, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.show_sql=true, hibernate.export.schema.delimiter=;, hibernate.bytecode.use_reflection_optimizer=false, hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy}
2015-01-16 08:56:54.322 INFO 27810 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2015-01-16 08:56:54.462 INFO 27810 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2015-01-16 08:56:54.499 INFO 27810 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2015-01-16 08:56:54.591 INFO 27810 --- [ main] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2015-01-16 08:56:54.751 INFO 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
Hibernate: alter table order drop constraint FK_m6q2ofkj1g5aobtb2p00ajpqg if exists
2015-01-16 08:56:54.752 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table order drop constraint FK_m6q2ofkj1g5aobtb2p00ajpqg if exists
2015-01-16 08:56:54.753 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : Syntax error in SQL statement "ALTER TABLE ORDER[*] DROP CONSTRAINT FK_M6Q2OFKJ1G5AOBTB2P00AJPQG IF EXISTS "; expected "identifier"; SQL statement:
alter table order drop constraint FK_m6q2ofkj1g5aobtb2p00ajpqg if exists [42001-176]
Hibernate: drop table customer if exists
Hibernate: drop table order if exists
2015-01-16 08:56:54.753 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: drop table order if exists
2015-01-16 08:56:54.753 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : Syntax error in SQL statement "DROP TABLE ORDER[*] IF EXISTS "; expected "identifier"; SQL statement:
drop table order if exists [42001-176]
Hibernate: create table customer (id bigint generated by default as identity, first_name varchar(255), last_name varchar(255), primary key (id))
Hibernate: create table order (id bigint generated by default as identity, amount double not null, customer_id bigint, primary key (id))
2015-01-16 08:56:54.756 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: create table order (id bigint generated by default as identity, amount double not null, customer_id bigint, primary key (id))
2015-01-16 08:56:54.756 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : Syntax error in SQL statement "CREATE TABLE ORDER[*] (ID BIGINT GENERATED BY DEFAULT AS IDENTITY, AMOUNT DOUBLE NOT NULL, CUSTOMER_ID BIGINT, PRIMARY KEY (ID)) "; expected "identifier"; SQL statement:
create table order (id bigint generated by default as identity, amount double not null, customer_id bigint, primary key (id)) [42001-176]
Hibernate: alter table order add constraint FK_m6q2ofkj1g5aobtb2p00ajpqg foreign key (customer_id) references customer
2015-01-16 08:56:54.757 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table order add constraint FK_m6q2ofkj1g5aobtb2p00ajpqg foreign key (customer_id) references customer
2015-01-16 08:56:54.757 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : Syntax error in SQL statement "ALTER TABLE ORDER[*] ADD CONSTRAINT FK_M6Q2OFKJ1G5AOBTB2P00AJPQG FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMER "; expected "identifier"; SQL statement:
alter table order add constraint FK_m6q2ofkj1g5aobtb2p00ajpqg foreign key (customer_id) references customer [42001-176]
2015-01-16 08:56:54.757 INFO 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2015-01-16 08:56:55.085 INFO 27810 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2015-01-16 08:56:55.102 INFO 27810 --- [ main] hello.Application : Started Application in 2.286 seconds (JVM running for 2.604)
Hibernate: insert into customer (id, first_name, last_name) values (null, ?, ?)
Hibernate: insert into customer (id, first_name, last_name) values (null, ?, ?)
Hibernate: insert into customer (id, first_name, last_name) values (null, ?, ?)
Hibernate: insert into customer (id, first_name, last_name) values (null, ?, ?)
Hibernate: insert into customer (id, first_name, last_name) values (null, ?, ?)
Hibernate: select customer0_.id as id1_0_, customer0_.first_name as first_na2_0_, customer0_.last_name as last_nam3_0_ from customer customer0_
Customers found with findAll():
-------------------------------
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=2, firstName='Chloe', lastName='O'Brian']
Customer[id=3, firstName='Kim', lastName='Bauer']
Customer[id=4, firstName='David', lastName='Palmer']
Customer[id=5, firstName='Michelle', lastName='Dessler']
Hibernate: select customer0_.id as id1_0_0_, customer0_.first_name as first_na2_0_0_, customer0_.last_name as last_nam3_0_0_ from customer customer0_ where customer0_.id=?
Customer found with findOne(1L):
--------------------------------
Customer[id=1, firstName='Jack', lastName='Bauer']
Hibernate: select customer0_.id as id1_0_, customer0_.first_name as first_na2_0_, customer0_.last_name as last_nam3_0_ from customer customer0_ where customer0_.last_name=?
Customer found with findByLastName('Bauer'):
--------------------------------------------
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=3, firstName='Kim', lastName='Bauer']
Hibernate: select customer0_.id as id1_0_, customer0_.first_name as first_na2_0_, customer0_.last_name as last_nam3_0_ from customer customer0_
Hibernate: delete from customer where id=?
Hibernate: delete from customer where id=?
Hibernate: delete from customer where id=?
Hibernate: delete from customer where id=?
Hibernate: delete from customer where id=?
2015-01-16 08:56:55.258 INFO 27810 --- [ main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#5d59e6f1: startup date [Fri Jan 16 08:56:53 CST 2015]; root of context hierarchy
2015-01-16 08:56:55.259 INFO 27810 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2015-01-16 08:56:55.260 INFO 27810 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2015-01-16 08:56:55.261 INFO 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
Hibernate: alter table order drop constraint FK_m6q2ofkj1g5aobtb2p00ajpqg if exists
2015-01-16 08:56:55.261 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table order drop constraint FK_m6q2ofkj1g5aobtb2p00ajpqg if exists
2015-01-16 08:56:55.261 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : Syntax error in SQL statement "ALTER TABLE ORDER[*] DROP CONSTRAINT FK_M6Q2OFKJ1G5AOBTB2P00AJPQG IF EXISTS "; expected "identifier"; SQL statement:
alter table order drop constraint FK_m6q2ofkj1g5aobtb2p00ajpqg if exists [42001-176]
Hibernate: drop table customer if exists
Hibernate: drop table order if exists
2015-01-16 08:56:55.263 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: drop table order if exists
2015-01-16 08:56:55.263 ERROR 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : Syntax error in SQL statement "DROP TABLE ORDER[*] IF EXISTS "; expected "identifier"; SQL statement:
drop table order if exists [42001-176]
2015-01-16 08:56:55.263 INFO 27810 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
Thoughts?
TIA,
- Ole
Try change your Order entity please:
package hello;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "order_table")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
protected Order() {}
double amount;
#ManyToOne
Customer customer;
}
Explanation:
Pay attention on #Table annotation. Using this annotation I've specified table name as order_table. In your case by default hibernate tried to generate table order. ORDER is service word in any sql. Exception appeared because hibernate was generating *** statement for the order table but db expected table name not service word order.
I had the exact same problem with an Order entity, solved defining explicitly the table name.
#Entity
#Table(name = "order_table")
class Order(
#Id
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
val orderId: String,
val customerId: String,
...
)
I had the same issue with a column named order but I was unable to change it. Adding backticks to the column annotation solved it.
#Column(name = "`ORDER`")
val order: String

Resources