I am creating a Spring Boot application. While I am running the application database table is not creating.
Here is my application.properties file
spring.datasource.url=jdbc:mysql://localhost/aymuws
spring.datasource.username=root
spring.datasource.password=1101289217
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
The User repository class
package com.technostack.aymuws.entities;
#Entity
#Table(name="user")
public class User {
#Id
#Email
#NotEmpty
#Column(unique=true)
private String email;
#Column(name="_name",unique=false,nullable=false,length=100)
#NotEmpty
private String name;
#Column(name="_password",unique=true,nullable=false)
#NotEmpty
#Size(max=12,min=6)
private String password;
#Column(name="_task")
#OneToMany(mappedBy="user",cascade=CascadeType.ALL)
private List<Task> tasks;
#Column(name="_roles")
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="USER_ROLES",joinColumns= {
#JoinColumn(name="USER_EMAIL",referencedColumnName="email")
},inverseJoinColumns= {
#JoinColumn(name="ROLE_NAME",referencedColumnName="name")
})
private List<Roles> roles;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
public List<Roles> getRoles() {
return roles;
}
public void setRoles(List<Roles> roles) {
this.roles = roles;
}
public User(String email, String name, String password) {
this.email = email;
this.name = name;
this.password = password;
}
public User() {
}
}
The Task repository class
package com.technostack.aymuws.entities;
#Entity
public class Task {
#Id
#GeneratedValue
private Long task_id;
#NotEmpty
private String date;
#NotEmpty
private String starttime;
#NotEmpty
private String stoptime;
#NotEmpty
private String description;
#ManyToOne
#JoinColumn(name="USER_EMAIL",referencedColumnName="email")
private User user;
// Constructors, setters & getters
}
And the Role repository class
package com.technostack.aymuws.entities;
#Entity
public class Roles {
#Id
private String name;
#ManyToMany(mappedBy="roles")
private List<User> users;
// Constructor, getters and setters
}
The Service class is the following.
package com.technostack.aymuws.service;
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public void createUser(User user) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
user.setPassword(encoder.encode(user.getPassword()));
Roles user_role = new Roles("USER");
List<Roles> create_role = new ArrayList<>();
create_role.add(user_role);
user.setRoles(create_role);
userRepository.save(user);
}
public void createAdmin(User user) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
user.setPassword(encoder.encode(user.getPassword()));
Roles user_role = new Roles("ADMIN");
List<Roles> create_role = new ArrayList<>();
create_role.add(user_role);
user.setRoles(create_role);
userRepository.save(user);
}
public User findone(String email) {
return userRepository.findOne(email);
}
}
Here is the console when I run the application.
00:33:34.875 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
00:33:34.881 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
00:33:34.882 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/D:/STS%204%20Project%20Workspace/Spring/AymuwsManagementSystem/target/classes/]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.20.RELEASE)
2019-04-22 00:33:35.898 INFO 6448 --- [ restartedMain] .t.a.i.AymuwsManagementSystemApplication : Starting AymuwsManagementSystemApplication on ADMIN-PC with PID 6448 (started by ADMIN in D:\STS 4 Project Workspace\Spring\AymuwsManagementSystem)
2019-04-22 00:33:35.901 INFO 6448 --- [ restartedMain] .t.a.i.AymuwsManagementSystemApplication : No active profile set, falling back to default profiles: default
2019-04-22 00:33:36.877 INFO 6448 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#143eb1f4: startup date [Mon Apr 22 00:33:36 IST 2019]; root of context hierarchy
2019-04-22 00:33:41.963 INFO 6448 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$f40d0ceb] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-04-22 00:33:43.478 INFO 6448 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-04-22 00:33:43.619 INFO 6448 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-04-22 00:33:43.620 INFO 6448 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.39
2019-04-22 00:33:43.986 INFO 6448 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-04-22 00:33:43.987 INFO 6448 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 7119 ms
2019-04-22 00:33:44.552 INFO 6448 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-04-22 00:33:44.553 INFO 6448 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-04-22 00:33:44.554 INFO 6448 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-04-22 00:33:44.554 INFO 6448 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2019-04-22 00:33:44.556 INFO 6448 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2019-04-22 00:33:44.557 INFO 6448 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
Mon Apr 22 00:33:45 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Apr 22 00:33:47 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Apr 22 00:33:47 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Apr 22 00:33:47 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Apr 22 00:33:47 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Apr 22 00:33:47 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Apr 22 00:33:47 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Apr 22 00:33:47 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Apr 22 00:33:47 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Apr 22 00:33:47 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2019-04-22 00:33:48.182 INFO 6448 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2019-04-22 00:33:48.246 INFO 6448 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-04-22 00:33:48.501 INFO 6448 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2019-04-22 00:33:48.504 INFO 6448 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-04-22 00:33:48.508 INFO 6448 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2019-04-22 00:33:48.622 INFO 6448 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2019-04-22 00:33:49.004 INFO 6448 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-04-22 00:33:49.642 INFO 6448 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2019-04-22 00:33:49.664 INFO 6448 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2019-04-22 00:33:49.758 INFO 6448 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-04-22 00:33:50.844 INFO 6448 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#143eb1f4: startup date [Mon Apr 22 00:33:36 IST 2019]; root of context hierarchy
2019-04-22 00:33:51.194 INFO 6448 --- [ 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)
2019-04-22 00:33:51.198 INFO 6448 --- [ 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)
2019-04-22 00:33:51.343 INFO 6448 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-04-22 00:33:51.344 INFO 6448 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-04-22 00:33:51.518 INFO 6448 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-04-22 00:33:51.654 WARN 6448 --- [ restartedMain] .t.AbstractTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2019-04-22 00:33:53.669 INFO 6448 --- [ restartedMain] b.a.s.AuthenticationManagerConfiguration :
Using default security password: 0ca7d39a-a92e-4e5b-a0e5-8ac4530d5849
2019-04-22 00:33:53.850 INFO 6448 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2019-04-22 00:33:54.145 INFO 6448 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#27ef81f6, org.springframework.security.web.context.SecurityContextPersistenceFilter#66a10a07, org.springframework.security.web.header.HeaderWriterFilter#3b89247c, org.springframework.security.web.authentication.logout.LogoutFilter#aa4c06d, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#13b8cd35, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#77d4b0f1, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#31591127, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#1245fcf2, org.springframework.security.web.session.SessionManagementFilter#15098ea6, org.springframework.security.web.access.ExceptionTranslationFilter#5e21e0fd, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#7ce8e89c]
2019-04-22 00:33:54.683 WARN 6448 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : Unable to start LiveReload server
2019-04-22 00:33:54.981 INFO 6448 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2019-04-22 00:33:55.109 INFO 6448 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2019-04-22 00:33:55.135 INFO 6448 --- [ restartedMain] .t.a.i.AymuwsManagementSystemApplication : Started AymuwsManagementSystemApplication in 20.199 seconds (JVM running for 21.509)
I am configuring all the database information in properties file. However, after executing the application I am not being able to create the database.
Change to this configuration in application.properties and see if its working
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/aymuws?autoReconnect=true&verifyServerCertificate=false&useSSL=false&requireSSL=false
Related
I am trying to run a basic spring boot application with JPA by using spanner emulator. However, I am getting the below error after startup after hitting any exposed end point.
PERMISSION_DENIED: com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: Caller is missing IAM permission spanner.sessions.create on resource projects/test-project/instances/test-instance/databases/test-database.
Project has been cloned from https://github.com/GoogleCloudPlatform/google-cloud-spanner-hibernate/tree/master/google-cloud-spanner-hibernate-samples/spring-data-jpa-sample
and the only change I have done is updated the application.properties file.
as per my understanding spanner emulator should not have any IAM related issues as it doesn't need any. I am not sure what is causing this issue here. I have verified that the emulator config is the active config and hence I would expect the code to connect to emulator.
# Application configuration to use Cloud Spanner with Spring Data JPA
# Spanner connection URL.
# - ${PROJECT_ID} Replace with your GCP project ID
# - ${INSTANCE_ID} Replace with your Spanner instance ID
# - ${DATABASE_NAME} Replace with your Spanner database name within your Spanner instance
spring.datasource.url=jdbc:cloudspanner:/projects/test-project/instances/test-instance/databases/test-database
# Specify the Spanner JDBC driver.
spring.datasource.driver-class-name=com.google.cloud.spanner.jdbc.JdbcDriver
# Specify the Spanner Hibernate dialect.
spring.jpa.properties.hibernate.dialect=com.google.cloud.spanner.hibernate.SpannerDialect
#spring.jpa.hibernate.ddl-auto=update //same error even if I uncomment this line
# Settings to enable batching statements for efficiency
spring.jpa.properties.hibernate.jdbc.batch_size=100
# You may display SQL statements and stats for debugging if needed.
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
Please find the console logs below:
2021-10-06 12:59:12.549 INFO 9747 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-10-06 12:59:12.556 INFO 9747 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-10-06 12:59:12.556 INFO 9747 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.53]
2021-10-06 12:59:12.617 INFO 9747 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-10-06 12:59:12.617 INFO 9747 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 694 ms
2021-10-06 12:59:12.707 INFO 9747 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-10-06 12:59:12.737 WARN 9747 --- [ main] c.g.a.oauth2.DefaultCredentialsProvider : Your application has authenticated using end user credentials from Google Cloud SDK. We recommend that most server applications use service accounts instead. If your application continues to use end user credentials from Cloud SDK, you might receive a "quota exceeded" or "API not enabled" error. For more information about service accounts, see https://cloud.google.com/docs/authentication/.
2021-10-06 12:59:14.558 INFO 9747 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not support get/set network timeout for connections. (Network timeout is not supported)
2021-10-06 12:59:22.165 INFO 9747 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-10-06 12:59:22.197 INFO 9747 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-10-06 12:59:22.231 INFO 9747 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.29.Final
2021-10-06 12:59:22.337 INFO 9747 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-10-06 12:59:22.396 INFO 9747 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: com.google.cloud.spanner.hibernate.SpannerDialect
2021-10-06 12:59:22.851 INFO 9747 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-10-06 12:59:22.857 INFO 9747 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-10-06 12:59:23.060 WARN 9747 --- [ 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
2021-10-06 12:59:23.184 INFO 9747 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2021-10-06 12:59:23.290 INFO 9747 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-10-06 12:59:23.298 INFO 9747 --- [ main] com.example.CoffeeApplication : Started CoffeeApplication in 12.957 seconds (JVM running for 13.227)
2021-10-06 12:59:33.646 INFO 9747 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-10-06 12:59:33.646 INFO 9747 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-10-06 12:59:33.647 INFO 9747 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Hibernate:
select
customer0_.id as id1_1_,
customer0_.email as email2_1_,
customer0_.name as name3_1_
from
customer customer0_
2021-10-06 12:59:35.650 WARN 9747 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 7, SQLState: null
2021-10-06 12:59:35.650 ERROR 9747 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : PERMISSION_DENIED: com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: Caller is missing IAM permission spanner.sessions.create on resource projects/test-project/instances/test-instance/databases/test-database.
2021-10-06 12:59:35.668 ERROR 9747 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
io.grpc.StatusRuntimeException: PERMISSION_DENIED: Caller is missing IAM permission spanner.sessions.create on resource projects/test-project/instances/test-instance/databases/test-database.
at io.grpc.Status.asRuntimeException(Status.java:535) ~[grpc-api-1.40.1.jar:1.40.1]
at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:533) ~[grpc-stub-1.40.1.jar:1.40.1]
at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39) ~[grpc-api-1.40.1.jar:1.40.1]
at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23) ~[grpc-api-1.40.1.jar:1.40.1]
at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40) ~[grpc-api-1.40.1.jar:1.40.1]
at com.google.cloud.spanner.spi.v1.SpannerErrorInterceptor$1$1.onClose(SpannerErrorInterceptor.java:100) ~[google-cloud-spanner-6.12.5.jar:6.12.5]
at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:557) ~[grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:69) ~[grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:738) ~[grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:717) ~[grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37) ~[grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133) ~[grpc-core-1.40.1.jar:1.40.1]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_281]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_281]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_281]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) ~[na:1.8.0_281]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_281]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_281]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_281]
The error is a clear indication that your application is not trying to connect to the emulator, but to a real Spanner database. In order to connect to the emulator instead of 'real' Cloud Spanner, you should do one of the following:
Set the environment variable SPANNER_EMULATOR_HOST=localhost:9010
OR: Edit the JDBC connection URL to include the autoConfigEmulator=true property. Your JDBC URL would then become jdbc:cloudspanner:/projects/test-project/instances/test-instance/databases/test-database;autoConfigEmulator=true
The advantage of the second alternative is that the autoConfigEmulator property will not only ensure that the JDBC driver is connecting to the emulator, it will also automatically create the test-instance and test-database on the emulator if they do not already exist.
I am having some issues in regards to my spring boot microservice, I have been able to successfully connect my microservice to my SQL instance running on Google Cloud, but for some reason when I try to test if the controllers are working using a sample endpoint which simply returns a String "Working" I get a 404 not found error, I have also tried a sample blank project, with no dependency except the ones needed to get Spring Boot up and running, however I still face the same problem, that is I get a 404 Not Found error, even though it is properly compiling and running. I have checked my firewall and it has not blocked the service.
Here is the Controller
VideoController.java
package com.example.demo.Controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class VideoController {
#RequestMapping(path = "/test")
public String index() {
return "Greetings from Spring Boot!";
}
}
Run Logs
2021-07-11 16:53:28.677 INFO 16456 --- [ main] com.example.demo.Run.DemoApplication : Starting DemoApplication using Java 15.0.2 on DESKTOP-OO1339O with PID 16456 (C:\Users\Engineering\IdeaProjects\gcp-demo\build\classes\java\main started by Engineering in C:\Users\Engineering\IdeaProjects\gcp-demo)
2021-07-11 16:53:28.679 INFO 16456 --- [ main] com.example.demo.Run.DemoApplication : No active profile set, falling back to default profiles: default
2021-07-11 16:53:29.149 INFO 16456 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-07-11 16:53:29.161 INFO 16456 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 5 ms. Found 0 JPA repository interfaces.
2021-07-11 16:53:29.510 INFO 16456 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-07-11 16:53:29.517 INFO 16456 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-07-11 16:53:29.517 INFO 16456 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.48]
2021-07-11 16:53:29.624 INFO 16456 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-07-11 16:53:29.625 INFO 16456 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 913 ms
2021-07-11 16:53:29.751 INFO 16456 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-07-11 16:53:29.788 INFO 16456 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-07-11 16:53:29.888 INFO 16456 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-07-11 16:53:29.971 INFO 16456 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-07-11 16:53:30.025 INFO 16456 --- [ main] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [XXXXXXXXHIDDENFROMSTACKOVERFLOWPOST] via SSL socket.
2021-07-11 16:53:30.025 INFO 16456 --- [ main] c.g.cloud.sql.core.CoreSocketFactory : First Cloud SQL connection, generating RSA key pair.
2021-07-11 16:53:31.820 INFO 16456 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-07-11 16:53:31.835 INFO 16456 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect
2021-07-11 16:53:31.924 INFO 16456 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [XXXXXXXXHIDDENFROMSTACKOVERFLOWPOST] via SSL socket.
2021-07-11 16:53:32.035 INFO 16456 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [XXXXXXXXHIDDENFROMSTACKOVERFLOWPOST] via SSL socket.
2021-07-11 16:53:32.040 INFO 16456 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-07-11 16:53:32.049 INFO 16456 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-07-11 16:53:32.099 WARN 16456 --- [ 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
2021-07-11 16:53:32.147 INFO 16456 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [XXXXXXXXHIDDENFROMSTACKOVERFLOWPOST] via SSL socket.
2021-07-11 16:53:32.245 INFO 16456 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [XXXXXXXXHIDDENFROMSTACKOVERFLOWPOST] via SSL socket.
2021-07-11 16:53:32.265 INFO 16456 --- [ main] c.g.c.s.core.DefaultCredentialsProvider : Default credentials provider for service account acn-demo-app#involuted-earth-319307.iam.gserviceaccount.com
2021-07-11 16:53:32.265 INFO 16456 --- [ main] c.g.c.s.core.DefaultCredentialsProvider : Scopes in use by default credentials: [https://www.googleapis.com/auth/pubsub, https://www.googleapis.com/auth/spanner.admin, https://www.googleapis.com/auth/spanner.data, https://www.googleapis.com/auth/datastore, https://www.googleapis.com/auth/sqlservice.admin, https://www.googleapis.com/auth/devstorage.read_only, https://www.googleapis.com/auth/devstorage.read_write, https://www.googleapis.com/auth/cloudruntimeconfig, https://www.googleapis.com/auth/trace.append, https://www.googleapis.com/auth/cloud-platform, https://www.googleapis.com/auth/cloud-vision, https://www.googleapis.com/auth/bigquery, https://www.googleapis.com/auth/monitoring.write]
2021-07-11 16:53:32.277 INFO 16456 --- [ main] c.g.c.s.a.c.GcpContextAutoConfiguration : The default project ID is XXXXXXXXHIDDENFROMSTACKOVERFLOWPOST
2021-07-11 16:53:32.353 INFO 16456 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [XXXXXXXXHIDDENFROMSTACKOVERFLOWPOST] via SSL socket.
2021-07-11 16:53:32.378 INFO 16456 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-07-11 16:53:32.389 INFO 16456 --- [ main] com.example.demo.Run.DemoApplication : Started DemoApplication in 4.027 seconds (JVM running for 4.567)
2021-07-11 16:53:32.449 INFO 16456 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [XXXXXXXXHIDDENFROMSTACKOVERFLOWPOST] via SSL socket.
2021-07-11 16:53:32.554 INFO 16456 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [XXXXXXXXHIDDENFROMSTACKOVERFLOWPOST] via SSL socket.
2021-07-11 16:53:32.659 INFO 16456 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [involuted-earth-319307:australia-southeast1:cloud-demo] via SSL socket.
2021-07-11 16:53:32.768 INFO 16456 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [XXXXXXXXHIDDENFROMSTACKOVERFLOWPOST] via SSL socket.
2021-07-11 16:53:38.167 INFO 16456 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-07-11 16:53:38.167 INFO 16456 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-07-11 16:53:38.168 INFO 16456 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
My Application Properties File
Application.properties
spring.main.allow-bean-definition-overriding=true
spring.datasource.url=SOMEVALUE HERE
spring.datasource.username=SOMEVALUE HERE
spring.datasource.password=SOMEVALUEHERE
spring.cloud.gcp.sql.database-name=SOMEVALUEHERE
spring.cloud.gcp.sql.instance-connection-name=SOMVEVALUEHERE
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
My File Structure
My Application Run Class
DemoApplication.Java
package com.example.demo.Run;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
DemoApplication is in the com.example.demo.Run package. This means that its component scanning, enabled via #SpringBootApplication, will find components in com.example.demo.Run and in any sub-packages such as com.example.demo.Run.example. The rest of your code, therefore, isn’t in a package where it’ll be found.
I would fix this by moving DemoApplication up into the com.example.demo package. This will mean that components in any of your existing com.example.demo.* packages is found.
Alternatively, you could leave DemoApplication where it is and use the scanBasePackages attribute on #SpringBootApplication to list all your other com.example.demo.* packages. This will be more verbose than moving DemoApplication and would require changes every time you introduce a new package.
As you said your first problem was because of the package level of your main class and Controller class. But the second problem does not seem to depend on refactoring the main class. It's related to conflict of the version of your JDK or another library
I have microservice projects access to a common config server. However the configuration for the Eugene client is working, but for the apache Kafka not working.
Spring Config server
#SpringBootApplication
#EnableEurekaClient
#EnableConfigServer
public class FeteBirdConfigurationServerApplication {
public static void main(String[] args) {
SpringApplication.run(FeteBirdConfigurationServerApplication.class, args);
}
}
bootstrap.yml
spring:
cloud:
config:
server:
git:
uri: https://github.com/anandjaisy/Microservice-Cloud-Config
Config server
spring:
application:
name: CONFIG-SERVER
server:
port: 8085
Git Repo
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
hostname: localhost
spring:
kafka:
producer:
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
Micoservice accessing config server
bootstrap.yml
spring:
cloud:
config:
uri:
- http://localhost:8085
If I put Kafka config in the microservice application.yml file the configuration works, but if I remove and try to access the config server it is not working.
spring:
application:
name: ORDER-SERVICE
kafka:
producer:
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
Logs from the microservice
2020-07-13 15:11:08.441 INFO 2025 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8085
2020-07-13 15:11:08.992 INFO 2025 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Connect Timeout Exception on Url - http://localhost:8085. Will be trying the next url if available
2020-07-13 15:11:08.999 WARN 2025 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8085/ORDER-SERVICE/dev": Connection refused; nested exception is java.net.ConnectException: Connection refused
2020-07-13 15:11:09.004 INFO 2025 --- [ restartedMain] f.b.f.FeteBirdOrderApplication : The following profiles are active: dev
2020-07-13 15:11:17.529 WARN 2025 --- [ restartedMain] o.s.boot.actuate.endpoint.EndpointId : Endpoint ID 'service-registry' contains invalid characters, please migrate to a valid format.
2020-07-13 15:11:18.328 INFO 2025 --- [ restartedMain] o.s.cloud.context.scope.GenericScope : BeanFactory id=0bb24ffe-2fc1-3960-867f-4b6e7735d255
2020-07-13 15:11:20.952 INFO 2025 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2020-07-13 15:11:21.095 INFO 2025 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-07-13 15:11:21.096 INFO 2025 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.36]
2020-07-13 15:11:21.612 INFO 2025 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-07-13 15:11:21.613 INFO 2025 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 12525 ms
2020-07-13 15:11:22.495 WARN 2025 --- [ restartedMain] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2020-07-13 15:11:22.495 INFO 2025 --- [ restartedMain] 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.
2020-07-13 15:11:22.541 INFO 2025 --- [ restartedMain] c.netflix.config.DynamicPropertyFactory : DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration#59982a7
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils (file:/Users/macbook/.gradle/caches/modules-2/files-2.1/org.springframework/spring-core/5.2.7.RELEASE/56e14a3a5e2813534b5db2da1502cd58ab5bc61d/spring-core-5.2.7.RELEASE.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2020-07-13 15:11:31.448 INFO 2025 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 17 endpoint(s) beneath base path '/actuator'
2020-07-13 15:11:32.508 WARN 2025 --- [ restartedMain] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2020-07-13 15:11:32.508 INFO 2025 --- [ restartedMain] 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.
2020-07-13 15:11:32.931 INFO 2025 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-07-13 15:11:33.094 WARN 2025 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : Unable to start LiveReload server
2020-07-13 15:11:34.161 WARN 2025 --- [ restartedMain] ockingLoadBalancerClientRibbonWarnLogger : You already have RibbonLoadBalancerClient on your classpath. It will be used by default. As Spring Cloud Ribbon is in maintenance mode. We recommend switching to BlockingLoadBalancerClient instead. In order to use it, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false` or remove spring-cloud-starter-netflix-ribbon from your project.
I have got this access denied exception :
java.sql.SQLException: Access denied for user ''#'localhost' (using
password: NO)
org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta-data; nested exception is
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to
obtain JDBC Connection; nested exception is java.sql.SQLException:
Access denied for user ''#'localhost' (using password: NO)
018-08-23 00:55:21.791 INFO 1260 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container
EntityManagerFactory for persistence unit 'default' 2018-08-23
00:55:21.813 INFO 1260 --- [ main]
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing
PersistenceUnitInfo [ name: default ...] 2018-08-23 00:55:22.180
INFO 1260 --- [ main] org.hibernate.Version
: HHH000412: Hibernate Core {5.2.17.Final} 2018-08-23 00:55:22.181
INFO 1260 --- [ main] org.hibernate.cfg.Environment
: HHH000206: hibernate.properties not found 2018-08-23 00:55:22.221
INFO 1260 --- [ main] o.hibernate.annotations.common.Version
: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 2018-08-23
00:55:22.351 INFO 1260 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-08-23 00:55:23.445 ERROR 1260 --- [ main]
com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception
during pool initialization.
application properties file:
spring.thymeleaf.cache=false
#===============================
#DATA SOURCE
#===============================
#set here configurations for the database connection
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredatabase?verifyServerCertificate=false&useSSL=true
#username and secret
spring.datasource.data.username=root
spring.datasource.data.password=
#keep connection alive if idle for long time
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
#===================
#jpa/hibernate
#===================
#use spring.jpa.properties.* for hibernate native properties
#stripped before adding them to the entity manager
#show or not log for each sql query
spring.jpa.show-sql=true
#jdbc driver class
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#the project
spring.jpa.hibernate.ddl-auto=create
#allows hibernate to generat sql optimised for particular dbms
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
my java file:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BookstoreApplication {
public static void main(String[] args) {
SpringApplication.run(BookstoreApplication.class, args);
}
}
It seems that your database username and password are not set with correct property names, as in spring-boot the name of the properties are predefined and only those should be used while giving configuration information. Just try below property keys for username and password :
spring.datasource.username =
spring.datasource.password =
Provide appropriate values..
java.sql.SQLException: Access denied for user ''#'localhost' (using password: NO)
It seems your user password is incorrect. Try to login MySQL with same credentials and it will display the same error.
I am trying to use embedded database derby with spring framework. I can insert the data and read it. Everything works completely fine except for one thing that the database is not persisting. When I close the application and run it again the data is not present. I am guessing that the database is created again but don't know why.
My code:
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class MainClass
{
#Bean
public DataSource dataSource()
{
// no need shutdown, EmbeddedDatabaseFactoryBean will take care of this
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder
.setType(EmbeddedDatabaseType.DERBY) //.HSQL, .H2 or .DERBY
.setName("some-db")
.addScript("/create-db.sql")
.build();
return db;
}
#Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource)
{
DataSourceTransactionManager d = new DataSourceTransactionManager(dataSource);
return d;
}
public static void main(String[] args)
{
ConfigurableApplicationContext context = new SpringApplicationBuilder(MainClass.class).headless(false).run(args);
MainFrame.mf = context.getBean(MainFrame.class);
MainFrame.mf.setVisible(true);
UserService userService = new UserService();
if(userService.isSignedIn())
{
MainFrame.mf.loggedIn();
}
else
{
MainFrame.mf.loggedOut();
}
}
}
And output logs by spring are
2017-09-17 20:41:53.461 INFO 3516 --- [ main] com.some.MainClass : Starting MainClass on maker with PID 3516 (C:\..\NetbeansProjects\..\target\classes started by verma in C:\..\NetbeansProjects\proj)
2017-09-17 20:41:53.469 INFO 3516 --- [ main] com.some.MainClass : No active profile set, falling back to default profiles: default
2017-09-17 20:41:53.571 INFO 3516 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2df32bf7: startup date [Sun Sep 17 20:41:53 IST 2017]; root of context hierarchy
2017-09-17 20:41:56.974 INFO 3516 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-09-17 20:41:57.007 INFO 3516 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-09-17 20:41:57.010 INFO 3516 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-09-17 20:41:57.278 INFO 3516 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-09-17 20:41:57.279 INFO 3516 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3714 ms
2017-09-17 20:41:57.606 INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-17 20:41:57.616 INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-17 20:41:57.618 INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-17 20:41:57.618 INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-17 20:41:57.619 INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-17 20:41:58.028 INFO 3516 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:derby:memory:some-db;create=true', username='sa'
2017-09-17 20:41:58.883 INFO 3516 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [create-db.sql]
2017-09-17 20:41:59.248 INFO 3516 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [create-db.sql] in 365 ms.
2017-09-17 20:42:00.907 INFO 3516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2df32bf7: startup date [Sun Sep 17 20:41:53 IST 2017]; root of context hierarchy
2017-09-17 20:42:01.052 INFO 3516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[POST]}" onto java.util.Map com.some.connection.ConnectionController.login(java.lang.String)
2017-09-17 20:42:01.055 INFO 3516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/logout],methods=[POST]}" onto org.springframework.http.ResponseEntity com.some.connection.ConnectionController.logout(java.lang.String)
2017-09-17 20:42:01.062 INFO 3516 --- [ 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-09-17 20:42:01.063 INFO 3516 --- [ 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-09-17 20:42:01.153 INFO 3516 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-17 20:42:01.155 INFO 3516 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-17 20:42:01.250 INFO 3516 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-17 20:42:01.717 INFO 3516 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-09-17 20:42:01.829 INFO 3516 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-09-17 20:42:01.840 INFO 3516 --- [ main] com.some.MainClass : Started MainClass in 9.034 seconds (JVM running for 9.794)
2017-09-17 20:42:06.305 INFO 3516 --- [ Thread-6] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2df32bf7: startup date [Sun Sep 17 20:41:53 IST 2017]; root of context hierarchy
2017-09-17 20:42:06.314 INFO 3516 --- [ Thread-6] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2017-09-17 20:42:06.348 INFO 3516 --- [ Thread-6] o.s.j.d.e.EmbeddedDatabaseFactory : Shutting down embedded database: url='jdbc:derby:memory:some-db;create=true'
create-db.sql contents are
CREATE TABLE table_connection
(
id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
ip VARCHAR(50) UNIQUE,
sessionId VARCHAR(50) DEFAULT NULL
);
SOLUTION:
Accepted answer pointed in right direction but the error was some-db;create=true failed to start. Then I looked at how Netbeans IDE was creating the derby connection. Problem was create=true, I think it's not supposed to be sent with the url but with properties as show in code below:
#Bean
public DataSource dataSource()
{
DriverManagerDataSource dm = new DriverManagerDataSource("jdbc:derby:some-db", "root", "root");
Properties properties = new Properties();
properties.setProperty("create", "true");
dm.setConnectionProperties(properties);
dm.setSchema("APP");
dm.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
return dm;
}
#Bean(name="Application.dataSourceInitializer")
public DataSourceInitializer dataSourceInitializer(DataSource dataSource)
{
final DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource);
try
{
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
jdbc.queryForList("SELECT id FROM table_connection");
}
catch(Exception e)
{
initializer.setDatabasePopulator(databasePopulator());
}
return initializer;
}
#Value("classpath:create-db.sql")
private Resource schemaScript;
private DatabasePopulator databasePopulator()
{
final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScript(schemaScript);
return populator;
}
Script create-db.sql can give error if table already exists as no IF EXISTS in derby so wrapped it in try-catch.
Bean datasourceInitializer is named explicitly 'Application.dataSourceInitializer' as spring auto-configuration tends to override it. Check it here.
This is the core of your problem: jdbc:derby:memory:some-db;create=true
When you say 'memory' in your Derby JDBC Connection URL, you are telling Derby explicitly to make a non-durable database.
If you remove the 'memory:' from your JDBC Connectino URL, Derby will create a persistent, durable database in the 'some-db' directory on your hard disk.