I am trying to run a code to get the details of user with a given id.
This is my code.
package com.in28minutes.database.databasedemo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.in28minutes.database.databasedemo.jpa.PersonJpaRepository;
#SpringBootApplication
public class JpaDemoApplication implements CommandLineRunner {
private Logger logger = LoggerFactory.getLogger(this.getClass());
#Autowired
PersonJpaRepository repository;
public static void main(String[] args) {
SpringApplication.run(JpaDemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
logger.info("User id 10001 -> {}", repository.findById(10001));
}
}
This is my repository:
package com.in28minutes.database.databasedemo.jpa;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.stereotype.Repository;
import com.in28minutes.database.databasedemo.entity.Person;
#Repository
#Transactional
public class PersonJpaRepository {
//connect to the database
#PersistenceContext
EntityManager entityManager;
public Person findById(int id) {
return entityManager.find(Person.class, id);
}
}
package com.in28minutes.database.databasedemo.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Person {
#Id
#GeneratedValue
private int id;
private String name;
private String location;
private Date birthDate;
public Person() {
}
public Person(int id, String name, String location, Date birthDate) {
super();
this.id = id;
this.name = name;
this.location = location;
this.birthDate = birthDate;
}
public Person(String name, String location, Date birthDate) {
super();
this.name = name;
this.location = location;
this.birthDate = birthDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
#Override
public String toString() {
return String.format("\nPerson [id=%s, name=%s, location=%s, birthDate=%s]", id, name, location, birthDate);
}
}
And this is my schema
create table person
(
id integer not null,
name varchar(255) not null,
location varchar(255),
birth_date timestamp,
primary key(id)
);
INSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE )
VALUES(10001, 'Ranga', 'Hyderabad',sysdate());
INSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE )
VALUES(10002, 'James', 'New York',sysdate());
INSERT INTO PERSON (ID, NAME, LOCATION, BIRTH_DATE )
VALUES(10003, 'Pieter', 'Amsterdam',sysdate());
I also have spring.h2.console.enabled=true in my application.properties.
2021-10-17 04:17:53.745 INFO 17096 --- [ main] c.i.d.databasedemo.JpaDemoApplication : Starting JpaDemoApplication using Java 16.0.2 on DESKTOP-Q0GM1GU with PID 17096 (C:\Users\HP\Desktop\database-demo\target\classes started by HP in C:\Users\HP\Desktop\database-demo)
2021-10-17 04:17:53.750 INFO 17096 --- [ main] c.i.d.databasedemo.JpaDemoApplication : No active profile set, falling back to default profiles: default
2021-10-17 04:17:55.170 INFO 17096 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-10-17 04:17:55.210 INFO 17096 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 14 ms. Found 0 JPA repository interfaces.
2021-10-17 04:17:57.110 INFO 17096 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-10-17 04:17:57.130 INFO 17096 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-10-17 04:17:57.130 INFO 17096 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.54]
2021-10-17 04:17:57.417 INFO 17096 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-10-17 04:17:57.418 INFO 17096 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3557 ms
2021-10-17 04:17:57.512 INFO 17096 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-10-17 04:17:57.924 INFO 17096 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-10-17 04:17:57.968 INFO 17096 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:0af42eb0-d2fc-45af-ad68-57b087b53fc0'
2021-10-17 04:17:58.592 INFO 17096 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-10-17 04:17:58.733 INFO 17096 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.0.Final
2021-10-17 04:17:59.180 INFO 17096 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-10-17 04:17:59.662 INFO 17096 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate: drop table if exists person CASCADE
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: create table person (id integer not null, birth_date timestamp, location varchar(255), name varchar(255), primary key (id))
2021-10-17 04:18:01.342 INFO 17096 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-10-17 04:18:01.368 INFO 17096 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-10-17 04:18:01.656 WARN 17096 --- [ 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-17 04:18:02.194 WARN 17096 --- [ main] o.s.w.s.r.ResourceHttpRequestHandler : Locations list is empty. No resources will be served unless a custom ResourceResolver is configured as an alternative to PathResourceResolver.
2021-10-17 04:18:02.550 INFO 17096 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-10-17 04:18:02.568 INFO 17096 --- [ main] c.i.d.databasedemo.JpaDemoApplication : Started JpaDemoApplication in 9.623 seconds (JVM running for 10.727)
Hibernate: select person0_.id as id1_0_0_, person0_.birth_date as birth_da2_0_0_, person0_.location as location3_0_0_, person0_.name as name4_0_0_ from person person0_ where person0_.id=?
2021-10-17 04:18:02.770 INFO 17096 --- [ main] ication$$EnhancerBySpringCGLIB$$6f304a0c : User id 10001 -> null
However, in my result, I am getting the value back as null. Also, I know that I should be getting an error that the table PERSON already exists and it that it should not be declared in the schema, but that is not the case.
After checking the h2 database, I see that none of the values are inserted.
You can try adding spring.jpa.hibernate.ddl-auto=create to your property file. You can check this question here in stackoverflow or from the documentation.
I am new to spring boot, i am getting this error since a while, unfortunately can't fix it. I am googling since then but still not find what i did wrong. Find below my code:
Entity
#Entity
#Table(name="compagnie")
public class Compagnie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_compagnie")
private int idCompagnie;
#Column(name="nom_compagnie")
private String nomCompagnie;
#Column(name="nom_court_compagnie")
private String nomCourtCompagnie;
#Column(name="logo_compagnie")
private String logoCompagnie;
public int getIdCompagnie() {
return idCompagnie;
}
public void setIdCompagnie(int idCompagnie) {
this.idCompagnie = idCompagnie;
}
public String getNomCompagnie() {
return nomCompagnie;
}
public void setNomCompagnie(String nomCompagnie) {
this.nomCompagnie = nomCompagnie;
}
public String getNomCourtCompagnie() {
return nomCourtCompagnie;
}
public void setNomCourtCompagnie(String nomCourtCompagnie) {
this.nomCourtCompagnie = nomCourtCompagnie;
}
public String getLogoCompagnie() {
return logoCompagnie;
}
public void setLogoCompagnie(String logoCompagnie) {
this.logoCompagnie = logoCompagnie;
}
}
Dao
#Component
public interface CompagnieDao extends JpaRepository<Compagnie, Integer> {
#Query("select c from Compagnie c where idCompagnie != :idCompagnie")
List<Compagnie> getAllCompagnieNonAssurAstuce(#Param("idCompagnie") int idCompagnie);
#Query("select c from Compagnie c where nomCompagnie = :nomCompagnie")
Compagnie getCompagnieByNom(#Param("nomCompagnie") String nomCompagnie);
}
Main
#SpringBootApplication
public class Application implements CommandLineRunner {
#Autowired
private CompagnieDao compagnieDao;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("tic toc");
List<Compagnie> compagnies = compagnieDao.findAll();
compagnies.forEach(compagnie -> System.out.println(compagnie.getNomCompagnie()));
}
}
Error
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-12-30 11:54:42.817 ERROR 10136 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Field compagnieDao in com.assurastuce.Application required a bean of type 'com.dao.CompagnieDao' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.dao.CompagnieDao' in your configuration.
Thank you for your help
I changed the spring version from 2.4.1 to 2.3.4.RELEASE and now getting this error
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at com.assurastuce.Application.main(Application.java:20) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_271]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_271]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_271]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_271]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.3.4.RELEASE.jar:2.3.4.RELEASE]
Caused by: java.lang.NullPointerException: null
at com.assurastuce.Application.run(Application.java:26) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
... 10 common frames omitted
2020-12-31 08:26:45.401 INFO 11520 --- [ restartedMain] o.e.jetty.server.AbstractConnector : Stopped ServerConnector#19b4bd36{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
2020-12-31 08:26:45.401 INFO 11520 --- [ restartedMain] org.eclipse.jetty.server.session : node0 Stopped scavenging
2020-12-31 08:26:45.405 INFO 11520 --- [ restartedMain] o.e.j.s.h.ContextHandler.application : Destroying Spring FrameworkServlet 'dispatcherServlet'
2020-12-31 08:26:45.407 INFO 11520 --- [ restartedMain] o.e.jetty.server.handler.ContextHandler : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext#4bfa6d74{application,/,[file:///C:/Users/LAKATAN%20Adebayo%20G.%20W/AppData/Local/Temp/jetty-docbase.8010039629830210588.8080/],UNAVAILABLE}
2020-12-31 08:26:45.430 INFO 11520 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-12-31 08:26:45.434 INFO 11520 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-12-31 08:26:45.438 INFO 11520 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-12-31 08:26:45.465 INFO 11520 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Probably the folder structure is not correct.
Could you please add this line of code and check if this works for you.
#SpringBootApplication
#ComponentScan(value = "com.dao.CompagnieDao")
public class Application implements CommandLineRunner {
Also, I think it would be more correct if you replace the #Component with the #Repository annotation.
#Repository
public interface CompagnieDao extends JpaRepository<Compagnie, Integer> {
trying to get foreign key one to many relationship in spring boot,but i'm not getting what is error and solution
Project struture
this is my user model class
package in.cubereum.Phoenix_backend.models;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.TableGenerator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.ToString;
#Entity
public class User {
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id", updatable = false, nullable = false)
private int user_id;
#Column(name = "active")
private boolean active;
#Column(name = "department")
private String department;
#Column(name = "division")
private String division;
#Column(name = "email")
private String email;
#Column(name = "employee_id")
private String employee_id;
#Column(name = "mobile_number")
private String mobile_number;
#Column(name = "first_name")
private String first_name;
#Column(name = "last_name")
private String last_name;
#Column(name = "nickname")
private String nickname;
#Column(name = "landline_number")
private String landline_number;
#Column(name = "role_id")
private String role_id;
#Column(name = "title")
private String title;
#Column(name = "city")
private String city;
#Column(name = "username")
private String username;
#Column(name = "passwords")
private String passwords;
#Column(name = "created_by")
private String created_by;
#Column(name = "created_date")
private Date created_date;
#Column(name = "modified_by")
private String modified_by;
#Column(name = "modified_date")
private Date modified_date;
#Column(name = "manager")
private String manager;
#JoinColumn(name = "org_id")
#OneToMany
#JsonIgnore
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
this is my organisation model class
package in.cubereum.Phoenix_backend.models;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.ToString;
#Entity
public class Organization {
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "org_id", updatable = false, nullable = false)
private int org_id;
#Column(name = "org_code") private int org_code;
#Column(name = "org_name") private String org_name;
#Column(name = "org_description") private String org_description;
#Column(name = "parent_org") private String parent_org;
#Column(name = "address") private String address;
#Column(name = "contact_number") private String contact_number;
#Column(name = "created_by") private String created_by;
#Column(name = "created_date") private Date created_date;
#Column(name = "last_modified_by") private String last_modified_by;
#Column(name = "last_modified_date") private Date last_modified_date;
#ManyToOne
private Set<User> roles = new HashSet<>(0);
public Set<User> getRoles() {
return roles;
}
public void setRoles(Set<User> roles) {
this.roles = roles;
}
}
this is my User service class
package in.cubereum.Phoenix_backend.endpoints;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import in.cubereum.Phoenix_backend.repository.Userrepository;
#RestController
#RequestMapping(path = "/main")
#Component
#CrossOrigin(origins = "*")
public class UserService {
#Autowired
private Userrepository userrepository;
}
this is my Organizationrepository Interface
package in.cubereum.Phoenix_backend.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import in.cubereum.Phoenix_backend.models.Organization;
#Repository
public interface Organizationrepository extends JpaRepository<Organization, String>{
}
this is my Userrepository
package in.cubereum.Phoenix_backend.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import in.cubereum.Phoenix_backend.models.User;
#Repository
public interface Userrepository extends JpaRepository<User, String>{
}
this is my main application class
package in.cubereum.Phoenix_backend;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#SpringBootApplication(scanBasePackages={"in.cubereum.Phoenix_backend.repository"})
#EnableJpaRepositories(basePackages = "in.cubereum.Phoenix_backend.repository")
public class Phoenix_backendApplication extends SpringBootServletInitializer{
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:");
}
};
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Phoenix_backendApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(Phoenix_backendApplication.class, args);
}
}
this is my build.gradle file
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
group = 'in.cubereum'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
dependencies {
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:23.0'
// This dependency is exported to consumers, that is to say found on their compile classpath.
// https://mvnrepository.com/artifact/org.apache.commons/commons-math3
compile group: 'org.apache.commons', name: 'commons-math3', version: '3.6.1'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
compile('org.springframework.boot:spring-boot-starter')
testCompile('org.springframework.boot:spring-boot-starter-test')
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.4.RELEASE'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent
compile group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '2.0.3.RELEASE', ext: 'pom'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.3.RELEASE'
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.47'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml
compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.9.6'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat:2.0.4.RELEASE'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-json
compile group: 'org.springframework.boot', name: 'spring-boot-starter-json', version: '2.0.5.RELEASE'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind'
// https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
compile group: 'com.googlecode.json-simple', name: 'json-simple'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools
compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.0.4.RELEASE'
// https://mvnrepository.com/artifact/org.hibernate/hibernate-core
compile group: 'org.hibernate', name: 'hibernate-core', version: '4.1.4.Final'
// https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api
compile group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2'
// https://mvnrepository.com/artifact/org.projectlombok/lombok
compile group: 'org.projectlombok', name: 'lombok', version: '1.16.6'
}
this is console output that i'm getting
17:36:28.478 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
17:36:28.481 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/, /spring-boot/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter/target/classes/]
17:36:28.481 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/home/cubereum/workspace/Phoenix_backend/bin/]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.3.RELEASE)
2018-10-04 17:36:29.008 INFO 20416 --- [ restartedMain] i.c.P.Phoenix_backendApplication : Starting Phoenix_backendApplication on cubereum with PID 20416 (/home/cubereum/workspace/Phoenix_backend/bin started by cubereum in /home/cubereum/workspace/Phoenix_backend)
2018-10-04 17:36:29.012 INFO 20416 --- [ restartedMain] i.c.P.Phoenix_backendApplication : No active profile set, falling back to default profiles: default
2018-10-04 17:36:29.140 INFO 20416 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#4eaf4b3d: startup date [Thu Oct 04 17:36:29 IST 2018]; root of context hierarchy
2018-10-04 17:36:31.116 INFO 20416 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d548bd60] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-10-04 17:36:31.675 INFO 20416 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-10-04 17:36:31.722 INFO 20416 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-10-04 17:36:31.722 INFO 20416 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-10-04 17:36:31.734 INFO 20416 --- [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: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
2018-10-04 17:36:31.841 INFO 20416 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-10-04 17:36:31.842 INFO 20416 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2710 ms
2018-10-04 17:36:32.041 INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-10-04 17:36:32.047 INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-10-04 17:36:32.047 INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-10-04 17:36:32.047 INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-10-04 17:36:32.048 INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-10-04 17:36:32.182 WARN 20416 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
2018-10-04 17:36:32.190 INFO 20416 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-10-04 17:36:32.225 INFO 20416 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-10-04 17:36:32.233 ERROR 20416 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
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.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:741) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[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 in.cubereum.Phoenix_backend.Phoenix_backendApplication.main(Phoenix_backendApplication.java:34) [bin/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.4.RELEASE.jar:2.0.4.RELEASE]
Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
at org.springframework.util.Assert.notEmpty(Assert.java:450) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.data.jpa.mapping.JpaMetamodelMappingContext.<init>(JpaMetamodelMappingContext.java:54) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:88) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:43) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.beans.factory.config.AbstractFactoryBean.afterPropertiesSet(AbstractFactoryBean.java:141) ~[spring-beans-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]
... 21 common frames omitted
I think you are use MyISAM engine, use InnoDB. It supports Foreign Keys.
Add this line to your application.properties
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL57InnoDBDialect
i am using springboot 1.4.4.RELEASE with mysql database
and the database configuration is as follows:
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?autoReconnect=true&useSSL=false
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
my main class:
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
my entity class (in sub package of main class) :
package org.spring.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
protected User() {}
public User(Long id) {
this.id= id;
}
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return String.format(
"User[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
startup logs:
2017-03-25 14:36:34.219 INFO 2816 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-03-25 14:36:34.245 INFO 2816 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-03-25 14:36:34.371 INFO 2816 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.11.Final}
2017-03-25 14:36:34.373 INFO 2816 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-03-25 14:36:34.375 INFO 2816 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-03-25 14:36:34.438 INFO 2816 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-03-25 14:36:34.854 INFO 2816 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-03-25 14:36:35.610 INFO 2816 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists user
Hibernate: create table user (id bigint not null auto_increment, first_name varchar(255), last_name varchar(255), primary key (id))
2017-03-25 14:36:35.633 INFO 2816 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-03-25 14:36:35.688 INFO 2816 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-03-25 14:36:36.704 INFO 2816 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4a9c188f: startup date [Sat Mar 25 14:36:30 AST 2017]; root of context hierarchy
the issue is that i see in the console that the create queries is generated but the table is not getting created, please advise why i am getting this and how to fix it.
It seems that your database url is not preceded with spring.datasource.url.
Also you dont seem to have the driver specified:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
And lastly make sure you have that driver as on of your dependencies in your pom.xml
It seems that the issue was from the eclipse downloading the artifacts, when i used maven command line to download the artifcats it worked fine !
my entity Client
#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(long code, String nom, String email, Collection<Compte> comptes) {
this.code = code;
this.nom = nom;
this.email = email;
this.comptes = comptes;
}
/...
getters and setters
}
entity Compte
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "TYPE_CPTE,",discriminatorType= DiscriminatorType.STRING,length = 2)
public abstract class Compte implements Serializable {
#Id
private String codeCompte;
private Date dataCreation;
private double solde;
#ManyToOne
#JoinColumn(name="CODE_CLI")
private Client client;
#OneToMany(mappedBy="compte")
private Collection<Operation> operations;
public Compte() {
super();
}
public Compte(String codeCompte, Date dataCreation, double solde, Client client, Collection<Operation> operations) {
this.codeCompte = codeCompte;
this.dataCreation = dataCreation;
this.solde = solde;
this.client = client;
this.operations = operations;
}
/...
getters and setters
}
entity Operation
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "TYPE_OP",discriminatorType = DiscriminatorType.STRING,length = 1)
public abstract class Operation implements Serializable{
#Id #GeneratedValue
private long numero;
private Date dateOperation;
private double montant;
#ManyToOne
#JoinColumn(name = "CODE_CPTE")
private Compte compte;
public Operation() {
super();
}
public Operation(Date dateOperation, double montant, Compte compte) {
this.dateOperation = dateOperation;
this.montant = montant;
this.compte = compte;
}
/...getters and setters
}
entity Retirer
#Entity
#DiscriminatorValue("R")
public class Retrait extends Operation {
public Retrait() {
}
public Retrait(Date dateOperation, double montant, Compte compte) {
super(dateOperation, montant, compte);
}
}
entity versement
#Entity
#DiscriminatorValue("V")
public class Versement extends Operation {
public Versement() {
}
public Versement(Date dateOperation, double montant, Compte compte) {
super(dateOperation, montant, compte);
}
}
entity Comptecourant
#Entity
#DiscriminatorValue("CE")
public class CompteEpargne extends Compte {
private double taux;
public CompteEpargne(String s, Date date, int i, Client c2, double taux) {
this.taux = taux;
}
public CompteEpargne(String codeCompte, Date dataCreation, double solde, Client client, Collection<Operation> operations, double taux) {
super(codeCompte, dataCreation, solde, client, operations);
this.taux = taux;
}
public CompteEpargne(){
super();
}
/...getters and setters
}
**entity CompteEpagne**
#Entity
#DiscriminatorValue("CC")
public class CompteCourant extends Compte {
private double decouvert;
public CompteCourant(String s, Date date, int i, Client c1, double decouvert) {
this.decouvert = decouvert;
}
public CompteCourant(String codeCompte, Date dataCreation, double solde, Client client, Collection<Operation> operations, double decouvert) {
super(codeCompte, dataCreation, solde, client, operations);
this.decouvert = decouvert;
}
public CompteCourant(){
super();
}
/...getters and setters
}
Repositorys
1
#Repository
public interface ClientRep extends JpaRepository<Client,Long> {
}
2
#Repository
public interface CompteRep extends JpaRepository<Compte,String> {
}
3
#Repository
public interface OperationRep extends JpaRepository<Operation,Long> {
#Query("select o from Operation o where o.compte.codeCompte=:x order by o.dateOperation desc ")
public Page<Operation> listOperation(String codeCpte, Pageable pageable);
}
service
public interface IBankMetier {
public Compte consulterCompte(String codeCpte);
public void verser(String codeCpte, double montant);
public void retirer(String codeCpte, double montant);
public void virement(String codeCpte1, String codeCpte2, double montant);
public Page<Operation> listOperation(String codeCpte, int page, int size);
}
implimantation
#Service
#Transactional
public class BankMetierImp implements IBankMetier {
#Autowired
private CompteRep compteRep;
#Autowired
private OperationRep operationRep;
#Override
public Compte consulterCompte(String codeCpte) {
Compte cp = compteRep.findOne(codeCpte);
if (cp == null) throw new RuntimeException("Compte introvable");
return cp;
}
#Override
public void verser(String codeCpte, double montant) {
Compte cp = consulterCompte(codeCpte);
Versement v = new Versement(new Date(), montant, cp);
operationRep.save(v);
cp.setSolde((cp.getSolde() + montant));
compteRep.save(cp);
}
#Override
public void retirer(String codeCpte, double montant) {
Compte cp = consulterCompte(codeCpte);
double facili = 0;
if (cp instanceof CompteCourant)
facili = ((CompteCourant) cp).getDecouvert();
if (cp.getSolde() + facili < montant)
throw new RuntimeException("solde insuffisant");
Retrait retrait = new Retrait(new Date(), montant, cp);
operationRep.save(retrait);
cp.setSolde((cp.getSolde() - montant));
compteRep.save(cp);
}
#Override
public void virement(String codeCpte1, String codeCpte2, double montant) {
retirer(codeCpte1, montant);
verser(codeCpte2, montant);
}
#Override
public Page<Operation> listOperation(String codeCpte, int page, int size) {
return operationRep.listOperation(codeCpte,new PageRequest(page,size));
}
}
Spring boot Application
#SpringBootApplication
public class MeinproApplication implements CommandLineRunner {
#Autowired
private ClientRep clientRep;
#Autowired
private CompteRep compteRep;
#Autowired
private OperationRep operationRep;
#Autowired
BankMetierImp bankMetier;
public static void main(String[] args) {
SpringApplication.run(MeinproApplication.class, args);
}
#Override
public void run(String... strings) throws Exception {
Client c1=clientRep.save(new Client("martin","martin#gmail.com"));
Client c2=clientRep.save(new Client("john","john#gmail.com"));
Compte cp1=compteRep.save(new CompteCourant("c1",new Date(),9000,c1,6000));
Compte cp2=compteRep.save(new CompteEpargne("c2",new Date(),63000,c2,12220));
operationRep.save(new Retrait(new Date(),6000,cp1));
operationRep.save(new Retrait(new Date(),10000,cp2));
operationRep.save(new Versement(new Date(),2000,cp1));
operationRep.save(new Versement(new Date(),20,cp2));
bankMetier.verser("c1",1000);
bankMetier.virement("c1","c2",2000);
}
}
application.properties
# DataSource settings:
spring.datasource.url=jdbc:mysql://localhost:3306/monbank
spring.datasource.username=roo
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
when I run it booom !!!!
2017-02-12 16:15:24.858 INFO 6232 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.0.11.Final}
2017-02-12 16:15:24.860 INFO 6232 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-02-12 16:15:24.863 INFO 6232 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-02-12 16:15:24.947 INFO 6232 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-02-12 16:15:25.113 INFO 6232 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-02-12 16:15:25.938 INFO 6232 --- [ restartedMain] org.hibernate.tuple.PojoInstantiator : HHH000182: No default (no-argument) constructor for class: meinpro.entiti.Client (class must be instantiated by Interceptor)
2017-02-12 16:15:26.209 INFO 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
Hibernate: alter table compte drop foreign key FK2hw4shqsxc782lychpkr52lmv
2017-02-12 16:15:26.228 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table compte drop foreign key FK2hw4shqsxc782lychpkr52lmv
2017-02-12 16:15:26.228 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Table 'monbank.compte' doesn't exist
Hibernate: alter table operation drop foreign key FKkr9nfjf0ipqrw5xwcf9jqq6gv
2017-02-12 16:15:26.229 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table operation drop foreign key FKkr9nfjf0ipqrw5xwcf9jqq6gv
2017-02-12 16:15:26.229 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Table 'monbank.operation' doesn't exist
Hibernate: drop table if exists client
Hibernate: drop table if exists compte
Hibernate: drop table if exists operation
Hibernate: create table client (code bigint not null auto_increment, email varchar(255), nom varchar(255), primary key (code))
Hibernate: create table compte (type_cpte, varchar(2) not null, code_compte varchar(255) not null, data_creation datetime, solde double precision not null, decouvert double precision, taux double precision, code_cli bigint, primary key (code_compte))
2017-02-12 16:15:26.712 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: create table compte (type_cpte, varchar(2) not null, code_compte varchar(255) not null, data_creation datetime, solde double precision not null, decouvert double precision, taux double precision, code_cli bigint, primary key (code_compte))
2017-02-12 16:15:26.713 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' varchar(2) not null, code_compte varchar(255) not null, data_creation datetime,' at line 1
Hibernate: create table operation (type_op varchar(1) not null, numero bigint not null auto_increment, date_operation datetime, montant double precision not null, code_cpte varchar(255), primary key (numero))
Hibernate: alter table compte add constraint FK2hw4shqsxc782lychpkr52lmv foreign key (code_cli) references client (code)
2017-02-12 16:15:27.146 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table compte add constraint FK2hw4shqsxc782lychpkr52lmv foreign key (code_cli) references client (code)
2017-02-12 16:15:27.147 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Table 'monbank.compte' doesn't exist
Hibernate: alter table operation add constraint FKkr9nfjf0ipqrw5xwcf9jqq6gv foreign key (code_cpte) references compte (code_compte)
2017-02-12 16:15:27.330 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table operation add constraint FKkr9nfjf0ipqrw5xwcf9jqq6gv foreign key (code_cpte) references compte (code_compte)
2017-02-12 16:15:27.331 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Can't create table `monbank`.`#sql-23d4_77` (errno: 150 "Foreign key constraint is incorrectly formed")
2017-02-12 16:15:27.332 INFO 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-02-12 16:15:27.414 INFO 6232 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-02-12 16:15:27.938 INFO 6232 --- [ restartedMain] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2017-02-12 16:15:28.776 INFO 6232 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2ffb82a2: startup date [Sun Feb 12 16:15:18 PST 2017]; root of context hierarchy
2017-02-12 16:15:28.936 INFO 6232 --- [ 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)
2017-02-12 16:15:28.938 INFO 6232 --- [ 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)
2017-02-12 16:15:29.022 INFO 6232 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-12 16:15:29.022 INFO 6232 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-12 16:15:29.112 INFO 6232 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-12 16:15:29.263 WARN 6232 --- [ restartedMain] .t.AbstractTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2017-02-12 16:15:30.063 INFO 6232 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2017-02-12 16:15:30.159 INFO 6232 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-02-12 16:15:30.246 INFO 6232 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
Hibernate: insert into client (email, nom) values (?, ?)
Hibernate: insert into client (email, nom) values (?, ?)
2017-02-12 16:15:30.461 INFO 6232 --- [ restartedMain] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-02-12 16:15:30.472 ERROR 6232 --- [ restartedMain] o.s.boot.SpringApplication : Application startup failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:779) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:760) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:747) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at meinpro.MeinproApplication.main(MeinproApplication.java:30) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.1.RELEASE.jar:1.5.1.RELEASE]
Caused by: org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save(): meinpro.entiti.Compte; nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): meinpro.entiti.Compte
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at com.sun.proxy.$Proxy86.save(Unknown Source) ~[na:na]
at meinpro.MeinproApplication.run(MeinproApplication.java:38) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
... 11 common frames omitted
Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): meinpro.entiti.Compte
at org.hibernate.id.Assigned.generate(Assigned.java:34) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:101) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:775) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:748) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:753) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at com.sun.proxy.$Proxy82.persist(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:508) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
... 22 common frames omitted
2017-02-12 16:15:30.478 INFO 6232 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2ffb82a2: startup date [Sun Feb 12 16:15:18 PST 2017]; root of context hierarchy
2017-02-12 16:15:30.483 INFO 6232 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2017-02-12 16:15:30.485 INFO 6232 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-02-12 16:15:30.485 INFO 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
Hibernate: alter table compte drop foreign key FK2hw4shqsxc782lychpkr52lmv
2017-02-12 16:15:30.488 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table compte drop foreign key FK2hw4shqsxc782lychpkr52lmv
2017-02-12 16:15:30.489 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Table 'monbank.compte' doesn't exist
Hibernate: alter table operation drop foreign key FKkr9nfjf0ipqrw5xwcf9jqq6gv
2017-02-12 16:15:30.499 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table operation drop foreign key FKkr9nfjf0ipqrw5xwcf9jqq6gv
2017-02-12 16:15:30.500 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Can't DROP 'FKkr9nfjf0ipqrw5xwcf9jqq6gv'; check that column/key exists
Hibernate: drop table if exists client
Hibernate: drop table if exists compte
Hibernate: drop table if exists operation
2017-02-12 16:15:30.879 INFO 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
Process finished with exit code 0
please help me
The error message is telling you exactly what the problem is
Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): meinpro.entiti.Compte
The id in your Compte class is not a generated value, like the other tables
#Id
private String codeCompte;
So you need to set this value yourself before you save it.
Now look at the CompteEpargne and the CompteCourant (which extend Compte) constructors
public CompteEpargne(String s, Date date, int i, Client c2, double taux) {
this.taux = taux;
}
public CompteEpargne(String codeCompte, Date dataCreation, double solde, Client client, Collection<Operation> operations, double taux) {
super(codeCompte, dataCreation, solde, client, operations);
this.taux = taux;
}
public CompteCourant(String s, Date date, int i, Client c1, double decouvert) {
this.decouvert = decouvert;
}
public CompteCourant(String codeCompte, Date dataCreation, double solde, Client client, Collection<Operation> operations, double decouvert) {
super(codeCompte, dataCreation, solde, client, operations);
this.decouvert = decouvert;
}
The first constructor of each type only sets one value, while the second calls the super constructor, which set all the values (id included). When you are saving, you are using the first constructor
Compte cp1=compteRep.save(new CompteCourant("c1",new Date(),9000,c1,6000));
Compte cp2=compteRep.save(new CompteEpargne("c2",new Date(),63000,c2,12220));
You are calling the constructor that only sets one value. So you probably need to fix how that those constructors are setting properties. Maybe you want to do something like
public CompteEpargne(String s, Date date, int i, Client c2, double taux) {
this(s, date, i, c2, new ArrayList<Operation>(), taux);
}
where you call the other constructor.
Simple Solution
Your id attribute is not set. This may be due to the fact that the DB field is not set to auto increment.
For MySQL (as you have given in Properties file) use this below sample for defining your POJO class.
#Id #GeneratedValue(strategy = GenerationType.IDENTITY) #Column(name="id", unique=true, nullable=false) public Long getId() { return this.id; }
thanks friends the problem is in the class Compte
#DiscriminatorColumn(name = "TYPE_CPTE,",discriminatorType= DiscriminatorType.STRING,length = 2)
with in the name is ="TYPE_CPTE," hhhh I dont see the comma after TYPE_CPTE
#DiscriminatorColumn(name = "TYPE_CPTE",discriminatorType= DiscriminatorType.STRING,length = 2)