The compilation of my SpringBoot app fails to create a database.
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'read bit, releaseDate date,
primary key (id)) engine=InnoDB' at line 1
According to the stack, it's from my "releaseDate" Date or my "read" boolean in my class "Book". I assume it fails with Jpa due to wrong annotations. (and that's pretty wide assumption, correct meif I am wrong)
Here is the stack
2019-01-21 14:29:21.482 INFO 5472 --- [ main] c.e.S.restapi.postgresql.Application : Starting Application on MSI with PID 5472 (D:\Documents\Coding\Grokonez\clientVue_appRestFulSpringBoot_dataPostGre\SpringBootRestPostgreSQL\target\classes started by Charles LeMagnifique in D:\Documents\Coding\Grokonez\clientVue_appRestFulSpringBoot_dataPostGre\SpringBootRestPostgreSQL)
2019-01-21 14:29:21.486 INFO 5472 --- [ main] c.e.S.restapi.postgresql.Application : No active profile set, falling back to default profiles: default
2019-01-21 14:29:22.216 INFO 5472 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-01-21 14:29:22.280 INFO 5472 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 58ms. Found 1 repository interfaces.
2019-01-21 14:29:22.565 INFO 5472 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$81d566ae] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-01-21 14:29:22.835 INFO 5472 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-01-21 14:29:22.855 INFO 5472 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-01-21 14:29:22.855 INFO 5472 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.14]
2019-01-21 14:29:22.861 INFO 5472 --- [ main] o.a.catalina.core.AprLifecycleListener : An older version [1.2.17] of the APR based Apache Tomcat Native library is installed, while Tomcat recommends a minimum version of [1.2.19]
2019-01-21 14:29:22.861 INFO 5472 --- [ main] o.a.catalina.core.AprLifecycleListener : Loaded APR based Apache Tomcat Native library [1.2.17] using APR version [1.6.3].
2019-01-21 14:29:22.861 INFO 5472 --- [ main] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2019-01-21 14:29:22.861 INFO 5472 --- [ main] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2019-01-21 14:29:23.900 INFO 5472 --- [ main] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.0.2o 27 Mar 2018]
2019-01-21 14:29:24.001 INFO 5472 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-01-21 14:29:24.001 INFO 5472 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2462 ms
2019-01-21 14:29:24.123 INFO 5472 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-01-21 14:29:24.628 INFO 5472 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-01-21 14:29:24.662 INFO 5472 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-01-21 14:29:24.711 INFO 5472 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.1.Final}
2019-01-21 14:29:24.712 INFO 5472 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-01-21 14:29:24.773 INFO 5472 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.3.Final}
2019-01-21 14:29:24.856 INFO 5472 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2019-01-21 14:29:24.901 INFO 5472 --- [ main] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
2019-01-21 14:29:25.448 WARN 5472 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "create table Book (id bigint not null, description longtext, name varchar(255), read bit, releaseDate date, primary key (id)) engine=InnoDB" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table Book (id bigint not null, description longtext, name varchar(255), read bit, releaseDate date, primary key (id)) engine=InnoDB" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:315) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:310) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1083) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:853) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at com.example.Spring.restapi.postgresql.Application.main(Application.java:10) ~[classes/:na]
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'read bit, releaseDate date, primary key (id)) engine=InnoDB' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.13.jar:8.0.13]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.13.jar:8.0.13]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.13.jar:8.0.13]
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:782) ~[mysql-connector-java-8.0.13.jar:8.0.13]
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:666) ~[mysql-connector-java-8.0.13.jar:8.0.13]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95) ~[HikariCP-3.3.0.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-3.3.0.jar:na]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.3.1.Final.jar:5.3.1.Final]
... 34 common frames omitted
My application.properties
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/books
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
My pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<optional>true</optional>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
my class Book
package com.example.Spring.restapi.postgresql.model;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
#Data
#Entity
//#Table(name = "table")
public class Book implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "name")
private String name;
#Column(name = "releaseDate")
#Temporal(TemporalType.DATE)
private Date releaseDate;
#Column(name = "read")
#NotNull
private boolean read;
#Lob
private String description;
public Book() {
}
public Book(String name, Date releaseDate) {
this.name = name;
this.releaseDate = releaseDate;
this.read = false;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
public boolean isRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
#Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", releaseDate=" + releaseDate +
", read=" + read +
'}';
}
}
Below are the solutions I have tried:
dialect MySQL8 in application.properties and pom.xml
last version of Hibernate core in pom.xml
adding annotations NotNull for boolean and Temporal for Date in my class Book
It seems that the problem is related to the READ reserved keyword, see :
Keywords and Reserved Words
Problem is read as name here if you change the read name to something else it will work fine:
#new query
CREATE TABLE Book (
id BIGINT NOT NULL,
description LONGTEXT,
name VARCHAR(255),
checked BIT, #little change
releaseDate DATE,
primary key (id)
) engine = InnoDB
//Code
#Column(name = "checked") //setting name to "checked"
private int read;
That is caused because there is a keyword READ in sql itself.
Changed to
#Column(name = "checked")
#NotNull
private boolean read;
Related
I am using spring data jpa with Oracle database. I am getting error even when I was not creating any data but when I was just testing the application. so error is same.
Error is
ERROR 22488 --- [ task-1] o.h.e.j.e.internal.JdbcEnvironmentImpl : Could not fetch the SequenceInformation from the database
java.sql.SQLException: Numeric Overflow at oracle.jdbc.driver.NumberCommonAccessor.throwOverflow(NumberCommonAccessor.java:4139
Below are the details.
DB table:-
create table product(
id int PRIMARY KEY,
name varchar2(20),
description varchar2(100),
price Number(8,3)
);
Entity class:-
#Data
#NoArgsConstructor
#Entity
public class Product {
#Id
private int id;
private String name;
#Column(name="description")
private String desc;
private Double price;
}
Repository class:-
public interface ProductRepository extends CrudRepository<Product, Integer> {
}
Runner class to run the application.
public class TestRunner implements CommandLineRunner {
#Autowired
private ProductRepository repo;
#Override
public void run(String... args) throws Exception {
System.out.println("Inside Runner class");
Product product= new Product();
product.setId(101);
product.setName("IPhone");
product.setDesc("Its Awesome");
product.setPrice(123.45d);
repo.save(product);
}
}
properties file:-
spring.datasource.url=jdbc:oracle:thin:#sca00tof.us.dell.com:1521:mfg1229
spring.datasource.username=apps
spring.datasource.password=apps
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
I am getting the below error.
2020-11-29 01:31:19.408 INFO 22488 --- [ main] c.l.s.product.ProductdataApplication : Starting ProductdataApplication using Java 14.0.2 on mahima-IN with PID 22488 (D:\Learning\spring\NewLearning\productdata\target\classes started by mahima-orcl in D:\Learning\spring\NewLearning\productdata)
2020-11-29 01:31:19.411 INFO 22488 --- [ main] c.l.s.product.ProductdataApplication : No active profile set, falling back to default profiles: default
2020-11-29 01:31:19.880 INFO 22488 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-11-29 01:31:19.930 INFO 22488 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 42 ms. Found 1 JPA repository interfaces.
2020-11-29 01:31:20.320 INFO 22488 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-11-29 01:31:20.365 INFO 22488 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-11-29 01:31:20.433 INFO 22488 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.24.Final
2020-11-29 01:31:20.455 INFO 22488 --- [ main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-11-29 01:31:20.594 INFO 22488 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-11-29 01:31:20.722 INFO 22488 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-11-29 01:31:23.745 INFO 22488 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-11-29 01:31:23.765 INFO 22488 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle12cDialect
2020-11-29 01:31:45.561 ERROR 22488 --- [ task-1] o.h.e.j.e.internal.JdbcEnvironmentImpl : Could not fetch the SequenceInformation from the database
java.sql.SQLException: Numeric Overflow
at oracle.jdbc.driver.NumberCommonAccessor.throwOverflow(NumberCommonAccessor.java:4139) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.NumberCommonAccessor.getLong(NumberCommonAccessor.java:636) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.GeneratedStatement.getLong(GeneratedStatement.java:208) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.GeneratedScrollableResultSet.getLong(GeneratedScrollableResultSet.java:261) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.GeneratedResultSet.getLong(GeneratedResultSet.java:560) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at com.zaxxer.hikari.pool.HikariProxyResultSet.getLong(HikariProxyResultSet.java) ~[HikariCP-3.4.5.jar:na]
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.resultSetMinValue(SequenceInformationExtractorLegacyImpl.java:134) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:60) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.sequenceInformationList(JdbcEnvironmentImpl.java:403) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:268) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1224) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1255) ~[hibernate-core-5.4.24.Final.jar:5.4.24.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.1.jar:5.3.1]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.1.jar:5.3.1]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.1.jar:5.3.1]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
your code is looking for GeneratedValue on id column since you are setting manually id value then you can create one more filed for primary key (jpa will take care of this field you need not to insert manually) like below:---
#NoArgsConstructor
#Entity
#Data
public class Product {
#Id
#GeneratedValue( strategy=GenerationType.SEQUENCE)
private int primaryId;
private int id;
private String name;
#Column(name="description")
private String desc;
private Double price;
}
I try to save object in Postgresql database but unsuccesfully. Application starts normally, no exception is thrown and companiesRepository is not null. The database has been created manually.
This is my Application.class:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
This is my Service.class:
#org.springframework.stereotype.Service
public class Service {
#Autowired
CompaniesRepository companiesRepository;
public void start() {
Companies companies = new Companies();
companies.setSomeString("some");
companies.setId(1);
companiesRepository.save(companies);
log.info("Companies saved in DB");
}
}
This is my Companies.class:
#Entity
#Data
public class Companies {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
Integer id;
String someString;
}
This is my CompaniesRepository interface:
#Repository
public interface CompaniesRepository extends CrudRepository<Companies, Integer> {
}
This is my Controller.class:
#RestController
public class Controller {
#Autowired
private Service service;
#RequestMapping("/")
public String start() throws Exception {
service.start();
return "App Started";
}
}
The configuration I have in bootstrap.yaml file works properly in another project:
spring:
jpa:
database-platform: org.hibernate.dialect.PostgreSQLDialect
show-sql: false
generate-ddl: true
time_zone: UTC
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
hbm2ddl:
auto: update
jdbc:
lob:
non_contextual_creation: true
enable_lazy_load_no_trans: true
datasource:
url: jdbc:postgresql://localhost:5432/dos?createDatabaseIfNotExist=true&serverTimezone=UTC
driver-class-name: org.postgresql.Driver
username: "postgres"
password: "123"
initialization-mode: always
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
jdbc:
time_zone: UTC
I tried to:
annottate String and id in Companies.class with #Column(nullable = false),
changed table name for Companies.class with #Table(name = "some_table").
add #Autowired CompaniesRepository repository; in Controller.class
EDIT:
Those are the console logs:
2020-03-07 15:35:11.620 INFO 2484 --- [ main] com.xtb.tradebot.Application : Starting Application on MWNB00049 with PID 2484 (C:\Users\Piotr\Documents\trade-bot\trade-bot\target\classes started by Piotr in C:\Users\Piotr\Documents\trade-bot\trade-bot)
2020-03-07 15:35:11.622 INFO 2484 --- [ main] com.xtb.tradebot.Application : No active profile set, falling back to default profiles: default
2020-03-07 15:35:12.179 INFO 2484 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-03-07 15:35:12.255 INFO 2484 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 63ms. Found 1 JPA repository interfaces.
2020-03-07 15:35:12.638 INFO 2484 --- [ 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-07 15:35:13.123 INFO 2484 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-07 15:35:13.137 INFO 2484 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-07 15:35:13.137 INFO 2484 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-03-07 15:35:13.226 INFO 2484 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-07 15:35:13.226 INFO 2484 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1563 ms
2020-03-07 15:35:13.390 INFO 2484 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-03-07 15:35:13.673 INFO 2484 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-03-07 15:35:13.735 INFO 2484 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-03-07 15:35:13.830 INFO 2484 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.4.10.Final}
2020-03-07 15:35:13.995 INFO 2484 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-03-07 15:35:14.131 INFO 2484 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-03-07 15:35:14.731 INFO 2484 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-03-07 15:35:14.735 INFO 2484 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-03-07 15:35:15.011 WARN 2484 --- [ 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-07 15:35:15.134 INFO 2484 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-07 15:35:15.369 INFO 2484 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-03-07 15:35:15.371 INFO 2484 --- [ main] com.xtb.tradebot.Application : Started Application in 4.035 seconds (JVM running for 4.357)
Logs after controller "/" endpoint called:
2020-03-07 16:28:40.365 INFO 20336 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-03-07 16:28:40.365 INFO 20336 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-03-07 16:28:40.374 INFO 20336 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 9 ms
This is pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.xtb</groupId>
<artifactId>trade-bot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>trade-bot</name>
<description>trade-bot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I deleted h2.database dependency and I added:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
And I added in bootstrap.yaml:
spring:
main:
allow-bean-definition-overriding: true
And now it works fine.
Spring doesn't create the table specified in my #Entity class in my MySQL database.
I've tried a lot of solutions given here in StackOverflow, like some changes in the application.properties, changing the dialect, setting up the schema etc. I've checked my database permissions and also the user/password information, and it's all fine.
application.properties:
spring.datasource.url=jdbc:mysql://localhost/MyBank?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>MyBanc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MyBanc</name>
<description>JEE spring boot Web Project by Zied </description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-security</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Client.java
package com.example.entities;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Collection;
#Entity
public class Client implements Serializable {
#Id #GeneratedValue
private long code;
private String nom;
private String email;
#OneToMany(mappedBy = "client",fetch = FetchType.LAZY)
private Collection<Compte> comptes;
public Client() {
super();
}
public Client(String nom, String email) {
super();
this.nom = nom;
this.email = email;
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Collection<Compte> getComptes() {
return comptes;
}
public void setComptes(Collection<Compte> comptes) {
this.comptes = comptes;
}
}
terminal:
2019-12-16 14:24:38.857 INFO 6812 --- [ restartedMain] com.example.MyBank.MyBankApplication : Starting MyBankApplication on DESKTOP-BLK0G7N with PID 6812 (C:\Users\ziedb\OneDrive\Bureau\aa\MyBank\target\classes started by Zied BenOthman in C:\Users\ziedb\OneDrive\Bureau\aa\MyBank)
2019-12-16 14:24:38.862 INFO 6812 --- [ restartedMain] com.example.MyBank.MyBankApplication : No active profile set, falling back to default profiles: default
2019-12-16 14:24:38.935 INFO 6812 --- [ restartedMain] o.s.b.devtools.restart.ChangeableUrls : The Class-Path manifest attribute in C:\Users\ziedb\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.2\jaxb-runtime-2.3.2.jar referenced one or more files that do not exist: file:/C:/Users/ziedb/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.xml.bind-api-2.3.2.jar,file:/C:/Users/ziedb/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/txw2-2.3.2.jar,file:/C:/Users/ziedb/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/istack-commons-runtime-3.0.8.jar,file:/C:/Users/ziedb/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/stax-ex-1.8.1.jar,file:/C:/Users/ziedb/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/FastInfoset-1.2.16.jar,file:/C:/Users/ziedb/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.activation-api-1.2.1.jar
2019-12-16 14:24:38.936 INFO 6812 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-12-16 14:24:38.936 INFO 6812 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-12-16 14:24:39.539 INFO 6812 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2019-12-16 14:24:39.557 INFO 6812 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10ms. Found 0 JPA repository interfaces.
2019-12-16 14:24:39.809 INFO 6812 --- [ restartedMain] 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)
2019-12-16 14:24:40.083 INFO 6812 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-12-16 14:24:40.091 INFO 6812 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-12-16 14:24:40.091 INFO 6812 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.29]
2019-12-16 14:24:40.169 INFO 6812 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-12-16 14:24:40.169 INFO 6812 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1233 ms
2019-12-16 14:24:40.288 INFO 6812 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2019-12-16 14:24:40.346 INFO 6812 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.4.9.Final}
2019-12-16 14:24:40.469 INFO 6812 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2019-12-16 14:24:40.627 INFO 6812 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-12-16 14:24:40.754 INFO 6812 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-12-16 14:24:40.769 INFO 6812 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-12-16 14:24:40.977 INFO 6812 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2019-12-16 14:24:40.984 INFO 6812 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-12-16 14:24:41.019 INFO 6812 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2019-12-16 14:24:41.072 WARN 6812 --- [ restartedMain] 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
2019-12-16 14:24:41.236 INFO 6812 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-12-16 14:24:41.388 WARN 6812 --- [ restartedMain] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2019-12-16 14:24:41.550 INFO 6812 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-12-16 14:24:41.553 INFO 6812 --- [ restartedMain] com.example.MyBank.MyBankApplication : Started MyBankApplication in 3.075 seconds (JVM running for 3.971)
Based on the tutorial that I'm following, this setup should result in the creation of the table in the MySQL database, but it doesn't happen.
There are some possible causes for this:
The application.properties file is not in the correct location. It
should be located in src/main/resources
Second problem: The entity class. You should add #Column on top of
the attributes
Move the entity package to become like org.example.entities and run
the app
In spring application you should create one pakcage for the one layer(entity, repository,service ...)
I think you can simplify this to achieve first a JDBC CRUD:
Remove all the unnecessary maven dependencies, only have following to begin with :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- in case you wanna add Junits-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
</plugin>
</plugins>
Then have following in your application.properties
spring.datasource.url=jdbc:mysql://localhost:yourMySQLPort/MyBank?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.jpa.hibernate.use-new-id-generator-mappings=false
spring.jpa.hibernate.ddl-auto=create
Take care of auto-generation of id of your entity:
#Entity
public class Client implements Serializable {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
private long code;
...
And to keep things simple initially, maintain the Main class i.e Spring boot starter class annotated with #SpringBootApplication in the same package as your entity Client
I've noticed that you haven't mentioned the MySQL server port in your URL, see if thats something that is not initiating the connection. Once you get this sorted, you can add up the rest of the features in your app (thymeleaf based viewing tech etc)
Hope this helps!
I am learning SpringBoot. using Spring JavaPersistenceAPI(JPA) and apache derby as the database. I am having trouble mapping a URL to a method.
I have Topics:
#Entity
public class Topic {
#Id
private String id;
private String name;
private String description;
public Topic() {
}
public Topic(String id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
} ... getters & setters...
And I have a Topic controller. It works fine:
#RestController
public class TopicController {
#Autowired
private TopicService topicServ;
#RequestMapping("/topics")
public List<Topic> getAllTopics() {
return topicServ.getAllTopics();
}
#RequestMapping("/topics/{topicId}")
public Topic getTopic(#PathVariable String topicId) {
return topicServ.getTopic(topicId);
}... more methods (they work fine)
Every topic has courses:
#Entity
public class Course {
private String id;
private String name;
private String description;
#ManyToOne
private Topic topic;
public Course() {
}
public Course(String id, String name, String description, String topicId) {
this.id = id;
this.name = name;
this.description = description;
this.setTopic(new Topic(topicId, "CourseConstructorNAME", "CourseConstructorDESCRIPTION"));
} ... getters & setters ...
And I have the courses controller, where I am finding the problem:
#RestController
public class CourseController {
#Autowired
private CourseService courseServ;
#GetMapping(value = "/topics/{topicId}/courses")
public List<Course> getAllCourses(#PathVariable("topicId") String topicId){
System.out.println("Hi"); *<-- does not print anything*
return courseServ.getAllCourses(topicId);
}
The problem is that, issuing a GET request to http://localhost:8080/topics/java/courses , returns a 404 error message:
{
"timestamp": "2018-11-26T19:30:08.871+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/topics/java/courses"
}
I expect a list of courses corresponding to the topic id fetched from the URL. The failure confuses me because the topic controller works fine and it is almost the same.
So, because the sysout I put above doesn't print anything, I must be doing something really dumb; but just in case, here is the code for courseServ:
#Service
public class CourseService {
#Autowired
private CourseRepository courseRepo;
public List<Course> getAllCourses(String topicId){
System.out.println("Calling get all courses from course service");
List<Course> theList = new ArrayList<Course>();
courseRepo.findByTopic_Id(topicId).forEach(theList::add);
System.out.println(theList.toString());
return theList;
}
and here is courseRepo:
public interface CourseRepository extends CrudRepository<Course, String> {
public List<Course> findByTopic_Id(String topicId);
}
Here is the spring console log:
2018-11-26 13:29:25.142 INFO 16252 --- [ main] P.ProjectNameWithJpaApplication : Starting ProjectNameWithJpaApplication on JulioPHX with PID 16252 (C:\SpringToolSuite\workspace\ProjectNameWithJPA\target\classes started by JulioPHX in C:\SpringToolSuite\workspace\ProjectNameWithJPA)
2018-11-26 13:29:25.148 INFO 16252 --- [ main] P.ProjectNameWithJpaApplication : No active profile set, falling back to default profiles: default
2018-11-26 13:29:27.107 INFO 16252 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2018-11-26 13:29:27.238 INFO 16252 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 116ms. Found 1 repository interfaces.
2018-11-26 13:29:28.254 INFO 16252 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c18d73e6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-11-26 13:29:29.466 INFO 16252 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-11-26 13:29:29.501 INFO 16252 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-11-26 13:29:29.502 INFO 16252 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/9.0.12
2018-11-26 13:29:29.525 INFO 16252 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_191\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_191/bin/server;C:/Program Files/Java/jre1.8.0_191/bin;C:/Program Files/Java/jre1.8.0_191/lib/amd64;C:\Scripts\;C:\;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Python37\;C:\Python37\Scripts;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Git\cmd;C:\Program Files\RedHat\java-1.8.0-openjdk-1.8.0.161-1\bin;C:\WINDOWS\System32\OpenSSH\;C:\MinGW\bin;C:\Program Files\MicrosoftVSCode\bin;C:\cygwin64\bin;C:\Program Files\apache-maven-3.5.4\bin;C:\Users\JulioPHX\AppData\Local\Microsoft\WindowsApps;;C:\Users\JulioPHX\Microsoft VS Code\bin;C:\SpringToolSuite\sts-bundle\sts-3.9.6.RELEASE;;.]
2018-11-26 13:29:29.773 INFO 16252 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-11-26 13:29:29.774 INFO 16252 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4461 ms
2018-11-26 13:29:29.852 INFO 16252 --- [ main] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-11-26 13:29:29.861 INFO 16252 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-11-26 13:29:29.862 INFO 16252 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-11-26 13:29:29.862 INFO 16252 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'formContentFilter' to: [/*]
2018-11-26 13:29:29.862 INFO 16252 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-11-26 13:29:30.698 INFO 16252 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-11-26 13:29:30.703 WARN 16252 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=org.apache.derby.jdbc.EmbeddedDriver was not found, trying direct instantiation.
2018-11-26 13:29:31.587 INFO 16252 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not support get/set network timeout for connections. (Feature not implemented: No details.)
2018-11-26 13:29:31.596 INFO 16252 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-11-26 13:29:31.764 INFO 16252 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-11-26 13:29:31.925 INFO 16252 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
2018-11-26 13:29:31.929 INFO 16252 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-11-26 13:29:32.247 INFO 16252 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2018-11-26 13:29:32.586 INFO 16252 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.DerbyTenSevenDialect
2018-11-26 13:29:34.603 WARN 16252 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "drop table topic" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "drop table topic" via JDBC Statement
Caused by: java.sql.SQLSyntaxErrorException: Schema 'SA' does not exist
Caused by: org.apache.derby.iapi.error.StandardException: Schema 'SA' does not exist
2018-11-26 13:29:34.718 INFO 16252 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#74b00247'
2018-11-26 13:29:34.725 INFO 16252 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-11-26 13:29:36.108 INFO 16252 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2018-11-26 13:29:36.251 WARN 16252 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : 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
2018-11-26 13:29:36.757 INFO 16252 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-26 13:29:36.763 INFO 16252 --- [ main] P.ProjectNameWithJpaApplication : Started ProjectNameWithJpaApplication in 12.543 seconds (JVM running for 13.617)
2018-11-26 13:29:42.083 INFO 16252 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2018-11-26 13:29:42.084 INFO 16252 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2018-11-26 13:29:42.100 INFO 16252 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 16 ms
2018-11-26 13:29:42.298 INFO 16252 --- [nio-8080-exec-1] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
And the pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>PackageNameWithJPA</groupId>
<artifactId>ProjectNameWithJPA</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ProjectNameWithJPA</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Project structure:
Thank you in advance for any help.
I have same problem .It is because your Properties default is set to:
"spring.jpa.hibernate.ddl-auto=create-drop"
change it
in application.properties file.if this not over there add this
"spring.jpa.hibernate.ddl-auto=update"
line in your application.properties file.It work fine.
Even I have encountered the same error while using Apache Derby. This is because of the default properties of spring which is -spring.jpa.hibernate.ddl-auto=create-drop.
Solution: Create an application.properties file in src/main/resources folder and change the property to spring.jpa.hibernate.ddl-auto=update and run the app again, it should work.
The reason being the second controller in package "ProjectNameWithJPA.course" is giving 404 error because spring is not able to scan controller in "ProjectNameWithJPA.course".
By default, Spring-Boot scans the controller under the same package hierarchy like it can be "PackageNameWithJPA.course"
Read this for more understanding spring docs [https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html]
You can always define a custom component scan in a spring boot project. By default #SpringBootApplication annotation handles the component scanning for the application. However, let’s say one of the components is defined in another package then you can define in your configuration class like :
#ComponentScan({"com.springboot.basics.springbootPA1","com.springboot.springbootPA2"})
#SpringBootApplication
public class testApplication{
I am just building a new App based on Spring-Boot 2.0.3.RELEASE, Hibernate and Java 9.
Since last night I had some issues for what I just have rebuilt it again to find step by step where the problem is located.
I am constantly facing the same issue and I cannot fix it by myself.
The Error:
2018-07-19 10:32:38.949 INFO 9080 --- [ main] com.tmtest.demo.DemoApplication : Starting DemoApplication on DESKTOP-MKTBJ7O with PID 9080 (D:\Git\test2\target\classes started by N-rG in D:\Git\test2)
2018-07-19 10:32:38.952 INFO 9080 --- [ main] com.tmtest.demo.DemoApplication : No active profile set, falling back to default profiles: default
2018-07-19 10:32:39.012 INFO 9080 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#2c07545f: startup date [Thu Jul 19 10:32:39 CEST 2018]; root of context hierarchy
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (file:/C:/Users/N-rG/.m2/repository/org/springframework/spring-core/5.0.7.RELEASE/spring-core-5.0.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$1
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
2018-07-19 10:32:39.967 INFO 9080 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$53763105] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-07-19 10:32:40.174 INFO 9080 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-07-19 10:32:40.198 INFO 9080 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-07-19 10:32:40.198 INFO 9080 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-07-19 10:32:40.207 INFO 9080 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [D:\Program Files\Java\jdk-10.0.1\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;D:\Program Files\nodejs\;D:\Program Files\Git\cmd;C:\Users\N-rG\AppData\Local\Programs\Python\Python36-32\Scripts\;C:\Users\N-rG\AppData\Local\Programs\Python\Python36-32\;C:\Users\N-rG\AppData\Local\Microsoft\WindowsApps;C:\Users\N-rG\AppData\Roaming\npm;.]
2018-07-19 10:32:40.279 INFO 9080 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-07-19 10:32:40.279 INFO 9080 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1272 ms
2018-07-19 10:32:40.372 INFO 9080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-07-19 10:32:40.372 INFO 9080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-07-19 10:32:40.372 INFO 9080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-07-19 10:32:40.372 INFO 9080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-07-19 10:32:40.372 INFO 9080 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-07-19 10:32:40.372 INFO 9080 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-07-19 10:32:40.467 INFO 9080 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-07-19 10:32:40.531 INFO 9080 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-07-19 10:32:40.557 INFO 9080 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-07-19 10:32:40.566 INFO 9080 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-07-19 10:32:40.603 INFO 9080 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.2.Final}
2018-07-19 10:32:40.604 INFO 9080 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-07-19 10:32:40.650 INFO 9080 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2018-07-19 10:32:40.727 INFO 9080 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2018-07-19 10:32:40.838 WARN 9080 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.tmtest.demo.Backend.Factory.FactoryWorker.factoryPublisher in com.tmtest.demo.Backend.Factory.FactoryPublisher.factoryWorkerList
2018-07-19 10:32:40.839 INFO 9080 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2018-07-19 10:32:40.849 INFO 9080 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2018-07-19 10:32:40.850 INFO 9080 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-07-19 10:32:40.860 INFO 9080 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-07-19 10:32:40.867 ERROR 9080 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.tmtest.demo.Backend.Factory.FactoryWorker.factoryPublisher in com.tmtest.demo.Backend.Factory.FactoryPublisher.factoryWorkerList
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1708) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:581) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:859) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at com.tmtest.demo.DemoApplication.main(DemoApplication.java:12) [classes/:na]
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.tmtest.demo.Backend.Factory.FactoryWorker.factoryPublisher in com.tmtest.demo.Backend.Factory.FactoryPublisher.factoryWorkerList
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:782) ~[hibernate-core-5.3.2.Final.jar:5.3.2.Final]
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:733) ~[hibernate-core-5.3.2.Final.jar:5.3.2.Final]
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:54) ~[hibernate-core-5.3.2.Final.jar:5.3.2.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1696) ~[hibernate-core-5.3.2.Final.jar:5.3.2.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1664) ~[hibernate-core-5.3.2.Final.jar:5.3.2.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:287) ~[hibernate-core-5.3.2.Final.jar:5.3.2.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904) ~[hibernate-core-5.3.2.Final.jar:5.3.2.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935) ~[hibernate-core-5.3.2.Final.jar:5.3.2.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) ~[spring-orm-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1767) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1704) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 16 common frames omitted
Process finished with exit code 1
My POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tmtest</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>10</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1-1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.3.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.2.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The FactoryPublisher class
#Entity
#Getter
#Setter
#EqualsAndHashCode
public class FactoryPublisher {
#OneToMany(mappedBy = "factoryPublisher", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private final List<FactoryWorker> factoryWorkerList = new ArrayList<>();
private final VirtualTimer virtualTimer = VirtualTimer.CounterFactory.getNewCounter();
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public FactoryPublisher() {
for (int i = 0; i < 2; i++) {
factoryWorkerList.add(new FactoryWorker());
}
new Thread(virtualTimer).start();
}
public synchronized void updateWorkers() {
factoryWorkerList.forEach(factoryWorker -> factoryWorker.updateWorker(virtualTimer.getCurrentValue()));
}
}
and the Worker:
#Entity
#Getter
#Setter
public class FactoryWorker {
#GeneratedValue(strategy = GenerationType.AUTO)
#Id
private long iD;
public void updateWorker(final int timeData) {
//System.out.println("worker: " + iD + " was updated with data: " + timeData);
}
}
the main:
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
The exception message is giving a hint already:
mappedBy reference an unknown target entity property: com.tmtest.demo.Backend.Factory.FactoryWorker.factoryPublisher in com.tmtest.demo.Backend.Factory.FactoryPublisher.factoryWorkerList
The mappedBy property can be used to define a bi-directional mapping, where you define the relation on one side (eg #ManyToOne) and use the mappedBy property on the other side so it knows how the relation works.
However, in your case you don't have a bi-directional mapping. In fact, you don't have a field called factoryPublisher in your FactoryWorker entity, so it can't resolve your mapping.
To solve this, you want to map the factoryPublisher field within FactoryWorker, for example:
#Entity
#Getter
#Setter
public class FactoryWorker {
#GeneratedValue(strategy = GenerationType.AUTO)
#Id
private long iD;
// Add this
#ManyToOne
private FactoryPublisher factoryPublisher;
// ...
}
Alternatively, if you don't want a bi-directional mapping, you can remove the mappedBy property on #OneToMany.