Spring boot jpa with H2 database - java

I am trying a sample code to run my Spring Boot data project with JPA for an H2 DB.
The code is below, application is running properly, but I don't see any table getting created, I don't see any error in the server console as well. I checked the logs, I don't see any queries getting created an fired. Am I am doing anything wrong?
Domain class:
#Entity
public class Account {
#Id
#GeneratedValue
private Integer accountId;
private String name;
private String accType;
public Integer getAccountId() {
return accountId;
}
public String getName() {
return name;
}
public String getAccType() {
return accType;
}
public Account(Integer accountId, String name, String accType) {
super();
this.accountId = accountId;
this.name = name;
this.accType = accType;
}
public Account(String name, String accType) {
super();
this.name = name;
this.accType = accType;
}
public Account() {
}
Data Loader class:
#Component
public class AccountLoaded {
private AccountRepository accountRepository;
public AccountLoaded(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
#PostConstruct
private void loadData() {
Account account = new Account(1,"Madhu","Savings");
accountRepository.save(account);
System.out.println("Loaded Account " + account.toString());
}
}
Repository class:
#Repository
public interface AccountRepository extends CrudRepository<Account, Integer> {
}
application.properties:
spring.datasource.jdbc-url=jdbc:h2:mem:test
spring.h2.console.enabled=true
spring.h2.console.path=/console
spring.datasource.platform=h2
My Logs in the server console:
2016-10-11 12:38:26.202 INFO 20020 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2016-10-11 12:38:26.217 INFO 20020 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2016-10-11 12:38:26.285 INFO 20020 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.11.Final}
2016-10-11 12:38:26.287 INFO 20020 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2016-10-11 12:38:26.288 INFO 20020 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2016-10-11 12:38:26.327 INFO 20020 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2016-10-11 12:38:26.554 INFO 20020 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2016-10-11 12:38:26.995 INFO 20020 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2016-10-11 12:38:27.004 INFO 20020 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2016-10-11 12:38:27.044 INFO 20020 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
Loaded Account Account [accountId=1, name=Madhu, accType=Savings]
2016-10-11 12:38:27.587 INFO 20020 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#b472aa: startup date [Tue Oct 11 12:38:23 CDT 2016]; root of context hierarchy
2016-10-11 12:38:27.663 INFO 20020 --- [ 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)
2016-10-11 12:38:27.664 INFO 20020 --- [ 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)
2016-10-11 12:38:27.696 INFO 20020 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-10-11 12:38:27.696 INFO 20020 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-10-11 12:38:27.732 INFO 20020 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-10-11 12:38:27.959 INFO 20020 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-10-11 12:38:28.011 INFO 20020 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-10-11 12:38:28.015 INFO 20020 --- [ main] com.example.SpringdataApplication : Started SpringdataApplication in 4.898 seconds (JVM running for 5.255)

Change spring.datasource.jdbc-url=jdbc:h2:mem:test to spring.datasource.jdbc-url=jdbc:h2:file:test (test is the name of the db file, could also have a path with the name) and use one of these tools to view the DB.
You can also log the SQL statements to your console, by adding spring.jpa.show-sql: true to your application.properties

If you go to the embedded h2 console (http://localhost:8080/console), and there type the correct connection URL (jdbc:h2:mem:test), you should see things.
The embedded h2 console does not show the correct connection URL by default, it forgets the :mem: part IIRC.

Even if all is done in memory you should see SQL logs when spring.jpa.show-sql is set to true (in application.properties file).
Don't forget to set spring.jpa.generate-ddl to true ( default is false) and make you loadData method transaction (see Spring #Transactional annotation).

Related

A component required a bean named 'dataSource' that could not be found

I am developing a simple Spring Batch jar using Spring Boot. I have used Configuration class to create dataSource bean and also annotated with #Component. But when I run the application using CommandLine Runner, it throws bean not found exception while reading the ABPBatchInfrastructure.xml.
I have did a little research of this error in google and found a solution, I have added below line in my ABPBatchInfrastructure.xml
<context:component-scan base-package="com.abp.printbatch"></context:component-scan>
Adding this line has fixed the issue but has other side effects
Spring is loading twice and all the spring core beans are getting instantiated twice.
I found this by checking the logs. Below logs for reference which shows same lines twice .
Spring JPA SQL statements are not showing up in the console even after adding spring.jpa.properties.hibernate.format_sql=true in the application-dev.properties.
is there a way to instantiate spring only once by removing the component scan in the xml and also fix the datasource bean not found issue. Please guide me. below log for your reference which clearly shows spring is loading twice.
2020-05-23 16:04:06.976 INFO 90732 --- [ main] c.a.p.FileUploadApplication : Starting FileUploadApplication on MW7CH1-FZXX with PID 90732 (C:\gitforABP\SpringBatch\target\classes started by cac6584 in C:\gitforABP\SpringBatch)
2020-05-23 16:04:06.979 INFO 90732 --- [ main] c.a.p.FileUploadApplication : The following profiles are active: dev
2020-05-23 16:04:07.672 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-23 16:04:07.752 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 69ms. Found 1 JPA repository interfaces.
2020-05-23 16:04:08.161 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-23 16:04:08.165 WARN 90732 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
2020-05-23 16:04:08.819 INFO 90732 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not support get/set network timeout for connections. (Receiver class oracle.jdbc.driver.T4CConnection does not define or inherit an implementation of the resolved method abstract getNetworkTimeout()I of interface java.sql.Connection.)
2020-05-23 16:04:08.870 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-23 16:04:08.923 INFO 90732 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-23 16:04:09.006 INFO 90732 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-05-23 16:04:09.152 INFO 90732 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-23 16:04:09.312 INFO 90732 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
2020-05-23 16:04:10.351 INFO 90732 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-23 16:04:10.364 INFO 90732 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-23 16:04:10.771 INFO 90732 --- [ main] c.a.p.FileUploadApplication : Started FileUploadApplication in 4.167 seconds (JVM running for 5.839)
2020-05-23 16:04:10.772 INFO 90732 --- [ main] c.a.p.FileUploadApplication : Local
2020-05-23 16:04:11.186 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-23 16:04:11.206 INFO 90732 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 19ms. Found 1 JPA repository interfaces.
2020-05-23 16:04:11.298 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Starting...
2020-05-23 16:04:11.298 WARN 90732 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
2020-05-23 16:04:11.663 INFO 90732 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-2 - Driver does not support get/set network timeout for connections. (Receiver class oracle.jdbc.driver.T4CConnection does not define or inherit an implementation of the resolved method abstract getNetworkTimeout()I of interface java.sql.Connection.)
2020-05-23 16:04:11.691 INFO 90732 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Start completed.
2020-05-23 16:04:11.706 INFO 90732 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-23 16:04:11.714 INFO 90732 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
2020-05-23 16:04:12.150 INFO 90732 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-23 16:04:12.151 INFO 90732 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-23 16:04:12.170 INFO 90732 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: ORACLE
2020-05-23 16:04:12.264 INFO 90732 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2020-05-23 16:04:12.465 WARN 90732 --- [ main] o.s.b.a.batch.JpaBatchConfigurer : JPA does not support custom isolation levels, so locks may not be taken when launching Jobs
2020-05-23 16:04:12.467 INFO 90732 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: ORACLE
2020-05-23 16:04:12.467 INFO 90732 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
Entry Point
#SpringBootApplication
#ComponentScan(basePackages = "com.abp.printbatch")
public class FileUploadApplication extends PrintBatchConstants implements CommandLineRunner {
#Autowired
private NotifyYaml notify;
final static Logger logger = LoggerFactory.getLogger(FileUploadApplication.class);
public static void main(String[] args) {
SpringApplication application = new SpringApplication(FileUploadApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
#Override
public void run(String... args) throws Exception {
logger.info(notify.getEnvironment());
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"ABPBatchInfrastructure.xml", "AgencyBillPayAppConfig.xml" );
JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
Job job=ctx.getBean(Job.class);
jobLauncher.run(job, new JobParametersBuilder()
.addString(documentClass,"InvoiceStatementDocumentation")
.addString(type, "2040-09-13")
.addString(emailID, notify.getSupportEmailId())
.addString(environment, notify.getEnvironment())
.toJobParameters());
ctx.close();
System.exit(0);
}
}
f
package com.abp.printbatch.config;
#Configuration
#Component
public class DBConfig {
#Bean
#Primary
public DataSource dataSource() {
System.out.println("");
return DataSourceBuilder.create().driverClassName("oracle.jdbc.driver.OracleDriver").url("removed")
.username("removed").password("removed").build();
}
}
As you mentioned, I have imported the xmls during app startup and removed application context initialization inside the run method. Also I removed component scan inside XML. This has fixed both datasource not found issue and Show SQL issue. Now application is working as expected. Below is my new entry point class. Thanks for all your help :)
#SpringBootApplication
#ComponentScan(basePackages = "com.abp.printbatch")
#ImportResource( { "ABPBatchInfrastructure.xml", "AgencyBillPayAppConfig.xml" } )
public class FileUploadApplication extends PrintBatchConstants implements CommandLineRunner {
#Autowired
private NotifyYaml notify;
#Autowired
private ApplicationContext ctx;
final static Logger logger = LoggerFactory.getLogger(FileUploadApplication.class);
public static void main(String[] args) {
SpringApplication application = new SpringApplication(FileUploadApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
#Override
public void run(String... args) throws Exception {
logger.info(notify.getEnvironment());
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"ABPBatchInfrastructure.xml", "AgencyBillPayAppConfig.xml" );
JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
Job job=ctx.getBean(Job.class);
jobLauncher.run(job, new JobParametersBuilder()
.addString(documentClass,"InvoiceStatementDocumentation") .addString(type,
"2040-09-13") .addString(emailID, notify.getSupportEmailId())
.addString(environment, notify.getEnvironment()) .toJobParameters());
ctx.close();
System.exit(0);
}
}

Cant reach Endpoint in Controller, despite it beeing intialised

I read this
and this
The main ideas are that somebody has the wrong structure and components are not beeing scanned, I have a correct one.
My controller is beeing initialised normaly. I tested it debugging and seting the breakpoint on the contructor. It is beiing runned. DEspite of the that the endpoint could not be reached by my tests nor by postman, nor in the browser. I am getting a 404.
I am using gradle. structured my code like this. Already spent 3 Hours trying to fix this, but without success.
My controller looks like this.
package com.fressnapf.microservices.orderhistory.controller.impl;
#RestController
#RequestMapping("/customer")
public class OrderHistoryController implements IOrderHistoryController {
...
#Override
#ResponseStatus(value = HttpStatus.OK)
#RequestMapping(value = "/{customerid}/orders}", method = RequestMethod.GET, produces = "application/json")
public String getOrders(#PathVariable("customerid") String customerid, #RequestParam(required = false) String timeFrom,
#RequestParam(required = false) String timeTo, #RequestParam(required = false) String openOnly) {
...
}
}
Aplplication class
package com.fressnapf.microservices.orderhistory;
#SpringBootApplication()
#ImportResource({"classpath*:applicationContext.xml"})
#Configuration()
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
this is the response I am getting
{
"timestamp": "2020-03-03T16:00:33.489+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/customer/000000000/orders"
}
this is the log I am getting in the app
2020-03-03 16:59:27.595 INFO 10406 --- [ main] c.f.m.orderhistory.Application : Starting Application on debian-sgtechedge with PID 10406 (/home/sergeygerodes/projects/scporderhistoryservice/build/classes/java/main started by sgerodes in /home/sergeygerodes/projects/scporderhistoryservice)
2020-03-03 16:59:27.602 INFO 10406 --- [ main] c.f.m.orderhistory.Application : No active profile set, falling back to default profiles: default
2020-03-03 16:59:28.414 INFO 10406 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-03-03 16:59:28.441 INFO 10406 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 16ms. Found 0 JPA repository interfaces.
2020-03-03 16:59:28.768 INFO 10406 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-03-03 16:59:29.035 INFO 10406 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-03 16:59:29.046 INFO 10406 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-03 16:59:29.047 INFO 10406 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.29]
2020-03-03 16:59:29.140 INFO 10406 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-03 16:59:29.140 INFO 10406 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1475 ms
2020-03-03 16:59:29.294 INFO 10406 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-03-03 16:59:29.405 INFO 10406 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-03-03 16:59:29.424 INFO 10406 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:orderhistory'
2020-03-03 16:59:29.517 INFO 10406 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-03-03 16:59:29.565 INFO 10406 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.4.9.Final}
2020-03-03 16:59:29.660 INFO 10406 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-03-03 16:59:29.741 INFO 10406 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-03-03 16:59:29.886 INFO 10406 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-03-03 16:59:29.892 INFO 10406 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-03-03 17:00:28.614 WARN 10406 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Thread starvation or clock leap detected (housekeeper delta=59s108ms538?s586ns).
2020-03-03 17:00:28.685 WARN 10406 --- [ 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-03-03 17:00:28.845 INFO 10406 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-03 17:00:29.052 INFO 10406 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-03-03 17:00:29.060 INFO 10406 --- [ main] c.f.m.orderhistory.Application : Started Application in 61.937 seconds (JVM running for 62.493)
2020-03-03 17:00:33.395 INFO 10406 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-03-03 17:00:33.395 INFO 10406 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-03-03 17:00:33.404 INFO 10406 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 9 ms
the whole applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="loggerService"
class="com.fressnapf.sdk.logger.service.impl.DefaultLogService" />
<bean id="dataService"
class="com.fressnapf.sdk.dataaccess.services.impl.H2DataProvider">
<constructor-arg index="0" value="${spring.datasource.url}"/>
<constructor-arg index="1" value="${spring.datasource.username}"/>
<constructor-arg index="2" value="${spring.datasource.password}"/>
</bean>
</beans>
If you copied your controller code and pasted it here...
There is a close bracket too much. I tested it on one of my controllers and it shows the same behaviour.
#RequestMapping(value = "/{customerid}/orders-->}<--"...

Query language problem with JPA +Hibernate+Mysql

I have developed a java stand alone application (java+hibernate) , now I am replanting which to java 8+springboot+jpa+hibernate+mysql framework. I used HQL in my old project, but there seems to be some problems with SQL sentences in the new framework , for example, I have to change "From p where id=(:parameter)" to "Select * from p where id=:parameter" by removing the bracket.
BEAN
#Entity
public class Place extends Groupunit_Defined implements Interface_Entity
{
......
#ManyToOne(targetEntity=Place_Definer.class)
#JoinColumn(name="Groupunit_Definer",nullable=false)
private Place_Definer Groupunit_Definer;//
.....
}
#Entity
public class Place_Definer extends Groupunit_Definer
{
......
#Column(nullable=false,length=150)
private String Classification;
…….
}
#SuppressWarnings("unchecked")
public ArrayList Simply_get_thing_list
(
String Query_String,
ArrayList Parameter_List,
Class Thing_Class
)
{
Query q=Entity_Manager.createNativeQuery(Query_String,Thing_Class);
…….
return Thing_List;
}
SQL SENTENCE
"SELECT * FROM Place p WHERE p.Groupunit_Definer.Classification='Jurisdiction'"
HIBERNATE CONFIG
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
ERROR MESSAGE
:: Spring Boot :: (v1.5.21.RELEASE)
2019-09-04 05:28:11.851 INFO 2508 --- [ main] c.s.mirrorworld.mirrorworldApplication : Starting mirrorworldApplication on LAPTOP-FAS0SHLM with PID 2508 (C:\Users\yueho\eclipse-workspace\mirrorworld\target\classes started by yueho in C:\Users\yueho\eclipse-workspace\mirrorworld)
2019-09-04 05:28:11.859 INFO 2508 --- [ main] c.s.mirrorworld.mirrorworldApplication : No active profile set, falling back to default profiles: default
2019-09-04 05:28:12.066 INFO 2508 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#2f217633: startup date [Wed Sep 04 05:28:12 CST 2019]; root of context hierarchy
2019-09-04 05:28:15.937 INFO 2508 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2019-09-04 05:28:15.994 INFO 2508 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-09-04 05:28:16.257 INFO 2508 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2019-09-04 05:28:16.260 INFO 2508 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-09-04 05:28:16.263 INFO 2508 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2019-09-04 05:28:16.559 INFO 2508 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2019-09-04 05:28:17.740 INFO 2508 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-09-04 05:28:19.002 WARN 2508 --- [ main] o.h.b.i.SessionFactoryBuilderImpl : Unrecognized hbm2ddl_auto value : update . Supported values include create, create-drop, update, and validate. Ignoring
2019-09-04 05:28:20.031 INFO 2508 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-09-04 05:28:24.577 INFO 2508 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2019-09-04 05:28:24.607 INFO 2508 --- [ main] c.s.mirrorworld.mirrorworldApplication : Started mirrorworldApplication in 13.439 seconds (JVM running for 24.733)
2019-09-04 05:28:33.326 INFO 2508 --- [WT-EventQueue-0] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2019-09-04 05:28:33.844 WARN 2508 --- [WT-EventQueue-0] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2019-09-04 05:28:33.845 ERROR 2508 --- [WT-EventQueue-0] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'p.Groupunit_Definer.Classification' in 'where clause'
Exception in thread "AWT-EventQueue-0" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at ……
org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:375)
at ……
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at …...
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'p.Groupunit_Definer.Classification' in 'where clause'
The problem has been solved by changing "createNativeQuery" to "createQuery", thank you to

Unable to create tables using spring data jpa in mysql

Spring JPA does not create the tables under the schema or MySql db.
#DataSource
spring.datasource.url=jdbc:mysql://localhost:3306/pickalystoredatabase?autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
The application properties seem to be perfect. I also do not see any errors in the logs
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "username", nullable = false)
private String username;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "firstname", nullable = false)
private String firstname;
#Column(name = "lastname", nullable = false)
private String lastname;
#Column(name = "email", nullable = false, updatable = false)
private String email;
#Column(name = "phone", nullable = false)
private String phone;
#Column(name = "enabled", nullable = false)
private boolean enabled = true;
public User() { }
//getters snad setters
}
I am using the spring-boot-started-data-jpa maven dependency. Version 1.5.9 RC.
Logs for your reference
The logs does not show any exception and it also does not have any information with respect to the creation of tables.
2018-01-31 00:18:53.662 INFO 6640
--- [ restartedMain] com.pickaly.application.Pickaly : Starting Pickaly on PHYADAVI-6Q4D5 with PID 6640 (C:\Users\phyadavi\pickaly\Pickaly-Store\target\classes started by phyadavi in C:\Users\phyadavi\pickaly\Pickaly-Store) 2018-01-31 00:18:53.662 INFO 6640
--- [ restartedMain] com.pickaly.application.Pickaly : No active profile set, falling back to default profiles: default 2018-01-31 00:18:53.664 INFO 6640
--- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5db9f92a: startup date [Wed Jan 31 00:18:53 IST 2018]; root of context hierarchy 2018-01-31 00:18:54.243 INFO 6640
--- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http) 2018-01-31 00:18:54.244 INFO 6640
--- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2018-01-31 00:18:54.244 INFO 6640
--- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23 2018-01-31 00:18:54.269 INFO 6640
--- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2018-01-31 00:18:54.270 INFO 6640
--- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 606 ms 2018-01-31 00:18:54.302 INFO 6640
--- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2018-01-31 00:18:54.302 INFO 6640
--- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2018-01-31 00:18:54.302 INFO 6640
--- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2018-01-31 00:18:54.302 INFO 6640
--- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2018-01-31 00:18:54.302 INFO 6640
--- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2018-01-31 00:18:54.443 INFO 6640
--- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default' 2018-01-31 00:18:54.443 INFO 6640
--- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ name: default ...] 2018-01-31 00:18:54.460 INFO 6640
--- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect 2018-01-31 00:18:54.467 INFO 6640
--- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update 2018-01-31 00:18:54.468 INFO 6640
--- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2018-01-31 00:18:54.553 INFO 6640
--- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5db9f92a: startup date [Wed Jan 31 00:18:53 IST 2018]; root of context hierarchy 2018-01-31 00:18:54.564 INFO 6640
--- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.pickaly.controllers.HomeController.index() 2018-01-31 00:18:54.567 INFO 6640
--- [ restartedMain] 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-01-31 00:18:54.567 INFO 6640
--- [ restartedMain] 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-01-31 00:18:54.574 INFO 6640
--- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-01-31 00:18:54.575 INFO 6640
--- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-01-31 00:18:54.587 INFO 6640
--- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-01-31 00:18:54.661 INFO 6640
--- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2018-01-31 00:18:54.705 INFO 6640
--- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2018-01-31 00:18:54.718 INFO 6640
--- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2018-01-31 00:18:54.720 INFO 6640
--- [ restartedMain] com.pickaly.application.Pickaly : Started Pickaly in 1.098 seconds (JVM running for 720.446)
Please help.
Edit:
In addition to the above mentioned properties i also used properties and annotations like
#EnableAutoConfiguration
#EntityScan(basePackages = {"com.pickaly.domains"})
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect instead of MySQLDBDialect
But these configurations did not work.
Try to add spring.jpa.generate-ddl = true to your application properties.

Camel - Can't access rest service

I'm running camel via spring and camel boot with embedded tomcat.
I have a simple camel route that is configuring correctly and consuming that I can see in the logs, but when i try to access it, it is giving 404 with localhost:8080/hi.
My Route
#Component
public class ServiceRoute extends RouteBuilder {
#Autowired
private SampleBean sampleBean;
#Override
public void configure() throws Exception {
from("rest:get:hi").to("bean:sampleBean");
}
}
My Main class
#Configuration
#SpringBootApplication
#ComponentScan(basePackages = { "routes", "service" },
excludeFilters = {#ComponentScan.Filter(value = Controller.class,
type = FilterType.ANNOTATION)})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Gradle dependencies
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
compile 'org.apache.camel:camel-spring-boot-starter:2.17.0'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-
web', version: '1.4.2.RELEASE'
compile group: 'org.apache.camel', name: 'camel-servlet', version:
'2.18.1'
}
Logs
2016-12-12 12:37:39.860 INFO 24684 --- [ main] root.Application : Starting Application on ram.tscpt.local with PID 24684 (/Users/srikanth/emulya/build/classes/main started by srikanth in /Users/srikanth/emulya)
2016-12-12 12:37:39.865 INFO 24684 --- [ main] root.Application : No active profile set, falling back to default profiles: default
2016-12-12 12:37:39.979 INFO 24684 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4facf68f: startup date [Mon Dec 12 12:37:39 SAST 2016]; root of context hierarchy
2016-12-12 12:37:41.866 INFO 24684 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.apache.camel.spring.boot.CamelAutoConfiguration' of type [class org.apache.camel.spring.boot.CamelAutoConfiguration$$EnhancerBySpringCGLIB$$a11fb1e5] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-12-12 12:37:42.597 INFO 24684 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-12-12 12:37:42.617 INFO 24684 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-12-12 12:37:42.618 INFO 24684 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.5
2016-12-12 12:37:42.756 INFO 24684 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-12-12 12:37:42.756 INFO 24684 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2782 ms
2016-12-12 12:37:42.959 INFO 24684 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-12-12 12:37:42.983 INFO 24684 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-12-12 12:37:42.984 INFO 24684 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-12-12 12:37:42.985 INFO 24684 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-12-12 12:37:42.985 INFO 24684 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-12-12 12:37:43.525 INFO 24684 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4facf68f: startup date [Mon Dec 12 12:37:39 SAST 2016]; root of context hierarchy
2016-12-12 12:37:43.651 INFO 24684 --- [ 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)
2016-12-12 12:37:43.653 INFO 24684 --- [ 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)
2016-12-12 12:37:43.703 INFO 24684 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-12 12:37:43.707 INFO 24684 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-12 12:37:43.778 INFO 24684 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-12 12:37:44.557 INFO 24684 --- [ main] o.a.c.i.converter.DefaultTypeConverter : Loaded 196 type converters
2016-12-12 12:37:44.890 INFO 24684 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-12-12 12:37:44.970 INFO 24684 --- [ main] o.a.camel.spring.boot.RoutesCollector : Loading additional Camel XML routes from: classpath:camel/*.xml
2016-12-12 12:37:44.973 INFO 24684 --- [ main] o.a.camel.spring.boot.RoutesCollector : Loading additional Camel XML rests from: classpath:camel-rest/*.xml
2016-12-12 12:37:44.974 INFO 24684 --- [ main] o.a.camel.spring.SpringCamelContext : Apache Camel 2.18.1 (CamelContext: camel-1) is starting
2016-12-12 12:37:44.976 INFO 24684 --- [ main] o.a.c.m.ManagedManagementStrategy : JMX is enabled
2016-12-12 12:37:45.548 INFO 24684 --- [ main] o.a.c.i.DefaultRuntimeEndpointRegistry : Runtime endpoint registry is in extended mode gathering usage statistics of all incoming and outgoing endpoints (cache limit: 1000)
2016-12-12 12:37:45.871 INFO 24684 --- [ main] o.a.camel.spring.SpringCamelContext : StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
2016-12-12 12:37:46.023 INFO 24684 --- [ main] o.a.camel.spring.SpringCamelContext : Route: route1 started and consuming from: servlet:/hi?httpMethodRestrict=GET
2016-12-12 12:37:46.024 INFO 24684 --- [ main] o.a.camel.spring.SpringCamelContext : Total 1 routes, of which 1 are started.
2016-12-12 12:37:46.026 INFO 24684 --- [ main] o.a.camel.spring.SpringCamelContext : Apache Camel 2.18.1 (CamelContext: camel-1) started in 1.050 seconds
2016-12-12 12:37:46.147 INFO 24684 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-12-12 12:37:46.157 INFO 24684 --- [ main] root.Application : Started Application in 6.985 seconds (JVM running for 7.475)
It's not working, because the Camel HTTP Servlet is not registered. CamelAutoConfiguration just starts the camel context.
You need to register the servlet yourself. The default name of the camel servlet is CamelServlet. Change your Application class:
#SpringBootApplication
#ComponentScan(basePackages = { "routes", "service" },
excludeFilters = {#ComponentScan.Filter(value = Controller.class,
type = FilterType.ANNOTATION)})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public ServletRegistrationBean servletRegistrationBean() {
ServletRegistrationBean registration = new ServletRegistrationBean(new CamelHttpTransportServlet(), "/service/*");
registration.setName("CamelServlet");
return registration;
}
}
And then try to access http://localhost/service/hi
Btw, you don't need to add #Configuration to the class annotated with #SpringBootApplication.

Categories