data.sql script for a H2 database is executing after my application is running for SpringBoot - spring-boot

I am assuming my data.sql script for a H2 database is executing after my application is running, hence, findById()(CRUD Methods) are not fetching any data(NULL). How can I fix this?
Please find my log details:
2020-10-12 18:52:01.361 INFO 30872 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-10-12 18:52:01.491 INFO 30872 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.21.Final
2020-10-12 18:52:01.735 INFO 30872 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-10-12 18:52:01.956 INFO 30872 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate: drop table if exists monitoring_app CASCADE
Hibernate: create table monitoring_app (id integer generated by default as identity, grep_parameter varchar(255), service_name varchar(255), hostname varchar(255), log_file_name varchar(255), log_file_path varchar(255), max_failed_retries integer not null, restart_sleep_time_secs integer not null, service_failure char(255), primary key (id))
2020-10-12 18:52:02.982 INFO 30872 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-10-12 18:52:02.990 INFO 30872 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
Hibernate: select monitoring0_.id as id1_0_, monitoring0_.grep_parameter as grep_par2_0_, monitoring0_.service_name as service_3_0_, monitoring0_.hostname as hostname4_0_, monitoring0_.log_file_name as log_file5_0_, monitoring0_.log_file_path as log_file6_0_, monitoring0_.max_failed_retries as max_fail7_0_, monitoring0_.restart_sleep_time_secs as restart_8_0_, monitoring0_.service_failure as service_9_0_ from monitoring_app monitoring0_ where monitoring0_.hostname=?
list is[]
Hibernate: select monitoring0_.id as id1_0_0_, monitoring0_.grep_parameter as grep_par2_0_0_, monitoring0_.service_name as service_3_0_0_, monitoring0_.hostname as hostname4_0_0_, monitoring0_.log_file_name as log_file5_0_0_, monitoring0_.log_file_path as log_file6_0_0_, monitoring0_.max_failed_retries as max_fail7_0_0_, monitoring0_.restart_sleep_time_secs as restart_8_0_0_, monitoring0_.service_failure as service_9_0_0_ from monitoring_app monitoring0_ where monitoring0_.id=?
Hibernate: insert into monitoring_app (id, grep_parameter, service_name, hostname, log_file_name, log_file_path, max_failed_retries, restart_sleep_time_secs, service_failure) values (null, ?, ?, ?, ?, ?, ?, ?, ?)
2020-10-12 18:52:03.679 INFO 30872 --- [ task-2] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-10-12 18:52:03.762 WARN 30872 --- [ 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
2020-10-12 18:52:04.283 INFO 30872 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-10-12 18:52:04.286 INFO 30872 --- [ restartedMain] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-10-12 18:52:04.287 INFO 30872 --- [ restartedMain] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-10-12 18:52:04.298 INFO 30872 --- [ restartedMain] c.m.automation.AutomationApplication : Started AutomationApplication in 7.785 seconds (JVM running for 8.729)
UPDATE:
Please find my data.sql
INSERT INTO EXAMPLE VALUES(default ,'a','b','c','d','e','f',1,2,'y');
INSERT INTO EXAMPLE VALUES(default ,'g','h','i','j','k','l',2,3,'n');
This is mu dao class
#Component
public class ExampleDao {
#Autowired
ExampleRepository exampleRepository;
public ArrayList<Example> dbFetchDetails(String var)
{
ArrayList<Example> exampleList = new ArrayList<>();
exampleList= exampleRepository.findByVar(var);
return exampleList;
}}
I extend my Repo with CRUDREPOSITORY and define findByVar()
#Repository
public interface ExampleRepository extends CrudRepository<Example, Integer> {
ArrayList<Example> findByVar(String Var);
}
#Entity
public class Example{
#Id #GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
private String a;
private String b;
private String c;
private String d;
private int e;
private int f;
private String g;
private String h;
private Character i;
//getters setters and contructors added
}

So as you said, your #PostConstruct methods are essentially executing before your data.sql executes and fills your local database with data. A simple way around that is to
Remove your #PostConstruct annotations from the methods that need the data.sql to run
Have the classes that have that were using the #PostConstruct methods implement ApplicationListener<ContextRefreshedEvent>
See example below
#Configuration
class InitConfiguration implements ApplicationListener<ContextRefreshedEvent> {
#Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
init();
}
//Your method that had your #PostConstruct annotation
public void init() {
// The code that needs the data.sql to run
}
}

Related

JPA ColumnTransformer write is not working

this is my entity.
#Getter
#Setter
#Entity
#Table(name = "crypt_test_table")
#IdClass(value = SqlFunctionTest.class) public class SqlFunctionTest implements Serializable {
#Id
private Long id;
#Column(name = "name")
#ColumnTransformer(
forColumn = "name",
read = "CONVERT(AES_DECRYPT(name, get_enc_key() ,get_aes_init_vector()) USING utf8)",
write = "AES_ENCRYPT(?, get_enc_key(), get_aes_init_vector())"
)
private String name;
}
I m trying to insert and select by encrypt and decrypt which I declared on my entity.
when I read it, it worked. like this.
SELECT
SQLFUNCTIO0_.ID AS ID1_13_,
SQLFUNCTIO0_.NAME AS NAME2_13_
FROM
CRYPT_TEST_TABLE SQLFUNCTIO0_
WHERE
CONVERT(AES_DECRYPT(SQLFUNCTIO0_.NAME, GET_ENC_KEY() ,GET_AES_INIT_VECTOR()) USING UTF8)='TROY.T'
but when i save an entity, it doesn't work like this.
INSERT
INTO
CRYPT_TEST_TABLE
(ID, NAME)
VALUES
(NULL, 'TROY.T')
This is the test code I did.
#Test
public void testSave(){
System.out.println("JPA TEST");
SqlFunctionTest entity = new SqlFunctionTest();
entity.setName("troy.t");
jpaCryptoService.save(entity);
}
#Test
public void testSelect(){
List<SqlFunctionTest> op = jpaCryptoService.findByName("troy.t");
System.out.println("op = " + op);
}
What's wrong with me?
2022-07-11T10:27:02.091+09:00 INFO 25748 --- [kground-preinit] o.h.v.i.u.Version : HV000001: Hibernate Validator 6.2.3.Final
2022-07-11T10:27:02.126+09:00 INFO 25748 --- [ main] ApplicationTest : Starting ApplicationTest using Java 11.0.14.1 on TroyTui-MacBookPro.local with PID 25748
2022-07-11T10:27:03.188+09:00 INFO 25748 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-07-11T10:27:03.592+09:00 INFO 25748 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 399 ms. Found 122 JPA repository interfaces.
2022-07-11T10:27:04.501+09:00 INFO 25748 --- [ main] c.z.h.HikariDataSource : HikariPool-1 - Starting...
2022-07-11T10:27:04.751+09:00 INFO 25748 --- [ main] c.z.h.HikariDataSource : HikariPool-1 - Start completed.
2022-07-11T10:27:04.829+09:00 INFO 25748 --- [ main] o.h.j.i.u.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-07-11T10:27:04.867+09:00 INFO 25748 --- [ main] o.h.Version : HHH000412: Hibernate ORM core version 5.6.9.Final
2022-07-11T10:27:04.996+09:00 INFO 25748 --- [ main] o.h.a.c.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-07-11T10:27:05.073+09:00 INFO 25748 --- [ main] o.h.d.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2022-07-11T10:27:05.564+09:00 WARN 25748 --- [ main] o.h.m.RootClass : HHH000038: Composite-id class does not override equals(): com.dktechin.saas.smartfactory.test.SqlFunctionTest
2022-07-11T10:27:05.564+09:00 WARN 25748 --- [ main] o.h.m.RootClass : HHH000039: Composite-id class does not override hashCode(): com.dktechin.saas.smartfactory.test.SqlFunctionTest
2022-07-11T10:27:06.228+09:00 INFO 25748 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-07-11T10:27:06.233+09:00 INFO 25748 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-07-11T10:27:10.167+09:00 INFO 25748 --- [ main] o.e.j.u.log : Logging initialized #9863ms to org.eclipse.jetty.util.log.Slf4jLog
2022-07-11T10:27:11.211+09:00 INFO 25748 --- [ main] ApplicationTest : Started ApplicationTest in 9.59 seconds (JVM running for 10.908)
JPA TEST
2022-07-11T10:27:11.393+09:00 INFO 25748 --- [ main] p6spy :
SELECT
SQLFUNCTIO0_.ID AS ID1_13_0_,
SQLFUNCTIO0_.NAME AS NAME2_13_0_
FROM
CRYPT_TEST_TABLE SQLFUNCTIO0_
WHERE
SQLFUNCTIO0_.ID=NULL
AND SQLFUNCTIO0_.NAME='TROY.T'
Connection ID: 2
Execution Time: 24 ms
Call Stack (number 1 is entry point):
----------------------------------------------------------------------------------------------------
2022-07-11T10:27:11.443+09:00 INFO 25748 --- [ main] p6spy :
INSERT
INTO
CRYPT_TEST_TABLE
(ID, NAME)
VALUES
(NULL, 'TROY.T')
Connection ID: 2
Execution Time: 14 ms
Call Stack (number 1 is entry point):
----------------------------------------------------------------------------------------------------
2022-07-11T10:27:11.602+09:00 INFO 25748 --- [ main] p6spy :
SELECT
SQLFUNCTIO0_.ID AS ID1_13_,
SQLFUNCTIO0_.NAME AS NAME2_13_
FROM
CRYPT_TEST_TABLE SQLFUNCTIO0_
WHERE
CONVERT(AES_DECRYPT(SQLFUNCTIO0_.NAME, GET_ENC_KEY() ,GET_AES_INIT_VECTOR()) USING UTF8)='TROY.T'
Connection ID: 3
Execution Time: 14 ms
Call Stack (number 1 is entry point):
----------------------------------------------------------------------------------------------------
op = []

Unable to insert values into h2 database table

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.

Spring-boot multiple databases - spring inserts data but only saves to one db

I've really been struggling with a multiple (2) db setup in springboot. I've spent countless of hours and followed many examples and I've read the complete documentation.
I find it hard to decide what should be added in my code because there are so many examples with different solutions around. There's Spring, Spring-boot, hibernate, jpa, beans, xml files, annotations, corrupt dependencies.
I've come up with a piece of code that doesn't give errors and saves my data. But, only the data to the primary database gets saved. The insert in the second db is happening according to the sql trace but no commit. What's going on here?
I also made a simple controller class to insert data with an http request, but it had the same results: only user in db1 gets saved, product in db2 doesn't.
If anybody has any clue it would be greatly appreciated. It's driving me nuts!
I realize this is just a simple piece of code, but it's test to see if I can use this approach in a bigger project.
Thanks!
the configuration:
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import com.multidb.db1.enitities.User;
import com.multidb.db2.entities.Product;
import javax.sql.DataSource;
#EnableJpaRepositories
public class DbConfiguration {
#Bean
#Primary
#ConfigurationProperties("spring.datasource")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#Primary
#ConfigurationProperties("spring.datasource.configuration")
public HikariDataSource firstDataSource() {
return firstDataSourceProperties().initializeDataSourceBuilder()
.type(HikariDataSource.class).build();
}
#Bean
#ConfigurationProperties("spring.datasource2")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#ConfigurationProperties("spring.datasource2.configuration")
public BasicDataSource secondDataSource() {
return secondDataSourceProperties().initializeDataSourceBuilder()
.type(BasicDataSource.class).build();
}
//////
#Primary
#Bean
public LocalContainerEntityManagerFactoryBean userEntityManagerFactory(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(firstDataSource())
.packages("db1")//User.class
.persistenceUnit("users")
.build();
}
#Bean
public LocalContainerEntityManagerFactoryBean productEntityManagerFactory(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondDataSource())
.packages("db2")//Product.class
.persistenceUnit("products")
.build();
}
}
the applicaton.properties file
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
spring.datasource.url=jdbc:mysql://localhost/db1?autoReconnect=true&useSSL=false
spring.datasource.username=user
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.configuration.maximum-pool-size=30
spring.datasource2.url=jdbc:mysql://localhost/db2?autoReconnect=true&useSSL=false
spring.datasource2.username=user
spring.datasource2.password=pass
spring.datasource2.driver-class-name=com.mysql.jdbc.Driver
spring.datasource2.max-total=30
a simple user class
import javax.persistence.*;
#Entity
#Table
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public User() {
//
}
}
and the product class
import javax.persistence.*;
#Entity
#Table
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Product() {
//
}
}
a user repo
import org.springframework.data.repository.CrudRepository;
import com.multidb.db1.enitities.User;
import org.springframework.transaction.annotation.Transactional;
#Transactional
public interface UserRepository extends CrudRepository<User, Long> {
//
}
a product repo
import com.multidb.db2.entities.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
public interface ProductRepository extends CrudRepository<Product, Long> {
//
}
a simple datainit class to write something to the db
import com.multidb.db1.repositories.UserRepository;
import com.multidb.db1.enitities.User;
import com.multidb.db2.entities.Product;
import com.multidb.db2.repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
#Component
public class InitData implements ApplicationRunner {
#Autowired
private ProductRepository productRepository;
#Autowired
private UserRepository userRepository;
#Autowired
public InitData(){}
#Override
public void run(ApplicationArguments args) throws Exception {
addUser("Johnny", "Depp");
addProduct("Booze", 5.0);
}
private void addUser(String firstname, String lastname){
User user = new User(firstname, lastname);
userRepository.save(user);
}
private void addProduct(String name, double price){
Product product = new Product(name, price);
productRepository.save(product);
}
}
the Maven dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
Last but not least the ouput
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2019-04-02 13:20:09.084 INFO 47275 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-04-02 13:20:09.147 INFO 47275 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 56ms. Found 2 repository interfaces.
2019-04-02 13:20:09.466 INFO 47275 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$84774c02] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-04-02 13:20:09.765 INFO 47275 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-04-02 13:20:09.795 INFO 47275 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-04-02 13:20:09.796 INFO 47275 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.16]
2019-04-02 13:20:09.805 INFO 47275 --- [ 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: [/Users/Fdoe/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2019-04-02 13:20:09.884 INFO 47275 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-04-02 13:20:09.885 INFO 47275 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1367 ms
2019-04-02 13:20:10.114 INFO 47275 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-04-02 13:20:10.327 INFO 47275 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-04-02 13:20:10.368 INFO 47275 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-04-02 13:20:10.423 INFO 47275 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
2019-04-02 13:20:10.424 INFO 47275 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-04-02 13:20:10.553 INFO 47275 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-04-02 13:20:10.684 INFO 47275 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-04-02 13:20:11.209 DEBUG 47275 --- [ main] org.hibernate.SQL : drop table if exists hibernate_sequence
Hibernate: drop table if exists hibernate_sequence
2019-04-02 13:20:11.220 DEBUG 47275 --- [ main] org.hibernate.SQL : drop table if exists product
Hibernate: drop table if exists product
2019-04-02 13:20:11.222 DEBUG 47275 --- [ main] org.hibernate.SQL : drop table if exists user
Hibernate: drop table if exists user
2019-04-02 13:20:11.225 DEBUG 47275 --- [ main] org.hibernate.SQL : create table hibernate_sequence (next_val bigint) engine=MyISAM
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
2019-04-02 13:20:11.228 DEBUG 47275 --- [ main] org.hibernate.SQL : insert into hibernate_sequence values ( 1 )
Hibernate: insert into hibernate_sequence values ( 1 )
2019-04-02 13:20:11.230 DEBUG 47275 --- [ main] org.hibernate.SQL : insert into hibernate_sequence values ( 1 )
Hibernate: insert into hibernate_sequence values ( 1 )
2019-04-02 13:20:11.231 DEBUG 47275 --- [ main] org.hibernate.SQL : create table product (id bigint not null, name varchar(255), price double precision not null, primary key (id)) engine=MyISAM
Hibernate: create table product (id bigint not null, name varchar(255), price double precision not null, primary key (id)) engine=MyISAM
2019-04-02 13:20:11.235 DEBUG 47275 --- [ main] org.hibernate.SQL : create table user (id bigint not null, first_name varchar(255), last_name varchar(255), primary key (id)) engine=MyISAM
Hibernate: create table user (id bigint not null, first_name varchar(255), last_name varchar(255), primary key (id)) engine=MyISAM
2019-04-02 13:20:11.239 INFO 47275 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#3a7c678b'
2019-04-02 13:20:11.241 INFO 47275 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-04-02 13:20:11.651 INFO 47275 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-02 13:20:11.695 WARN 47275 --- [ 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
2019-04-02 13:20:11.889 INFO 47275 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-02 13:20:11.891 INFO 47275 --- [ main] com.fdoe.multidb.Application : Started Application in 3.92 seconds (JVM running for 4.308)
2019-04-02 13:20:11.913 DEBUG 47275 --- [ main] org.hibernate.SQL : select next_val as id_val from hibernate_sequence for update
Hibernate: select next_val as id_val from hibernate_sequence for update
2019-04-02 13:20:11.928 DEBUG 47275 --- [ main] org.hibernate.SQL : update hibernate_sequence set next_val= ? where next_val=?
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
2019-04-02 13:20:11.948 DEBUG 47275 --- [ main] org.hibernate.SQL : insert into user (first_name, last_name, id) values (?, ?, ?)
Hibernate: insert into user (first_name, last_name, id) values (?, ?, ?)
2019-04-02 13:20:11.950 TRACE 47275 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [Johnny]
2019-04-02 13:20:11.950 TRACE 47275 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [Depp]
2019-04-02 13:20:11.951 TRACE 47275 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [BIGINT] - [1]
2019-04-02 13:20:11.957 DEBUG 47275 --- [ main] org.hibernate.SQL : select next_val as id_val from hibernate_sequence for update
Hibernate: select next_val as id_val from hibernate_sequence for update
2019-04-02 13:20:11.958 DEBUG 47275 --- [ main] org.hibernate.SQL : update hibernate_sequence set next_val= ? where next_val=?
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
2019-04-02 13:20:11.959 DEBUG 47275 --- [ main] org.hibernate.SQL : insert into product (name, price, id) values (?, ?, ?)
Hibernate: insert into product (name, price, id) values (?, ?, ?)
2019-04-02 13:20:11.959 TRACE 47275 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [Booze]
2019-04-02 13:20:11.960 TRACE 47275 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [DOUBLE] - [5.0]
2019-04-02 13:20:11.960 TRACE 47275 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [BIGINT] - [2]
db1 - terminal/command line output
mysql> select * from user;
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1 | Johnny | Depp |
+----+------------+-----------+
1 row in set (0.00 sec)
mysql>
db2 - terminal/command line output
mysql> select * from product;
Empty set (0.01 sec)
mysql>
You have not included Product Repository and User Repository class,please check the annotation in the class
Did you use Entity Manager
if Yes then
Did you use #PersistenceContext annotation for the entity manager
please follow the below example,try to run it on your local by just copy pasting the code and seeing the configuration
Spring Boot + JPA
if you have used CRUD Repository
You can refer to the below code
Spring Boot+CRUD Repository+JPA
Both are running in my local

Hibernate Validation does not look up error messages in a Spring boot application

This is my Spring boot project set up.
I have a standard Spring boot JPA stack in which I am trying to validate the state of the instance variables. My bean is as follows:
Configuration
#Component
public class ConfigurationHelper {
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("messages");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setCacheSeconds(5);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public Validator validator() {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
factoryBean.setValidationMessageSource(this.messageSource());
return factoryBean;
}
}
Model class
#Table(name = "user_station", indexes = {
#Index(columnList = "station_id", name = "station_index_station_id"),
#Index(columnList = "station_name", name="station_index_name"),
#Index(columnList = "hd_enabled", name = "station_index_hd_enabled")
})
#Entity
#EqualsAndHashCode(exclude = {"createdTimeStamp", "updatedTimestamp"}, callSuper = true)
#ToString(exclude = {"createdTimeStamp", "updatedTimestamp"}, callSuper = true)
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Station extends IError {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#JsonIgnore
private Long id;
// Represents a station id for the user.
#Column(name="station_id", nullable = false, unique = true)
#NotEmpty(message = "{station.id.empty}")
#Pattern(regexp = "^K|W[A-Za-z0-9\\-].*$", message = "{station.id.name.not.valid}")
private String stationId;
#Column(name="station_name", nullable = false)
#JsonProperty("name")
#NotEmpty(message = "{station.name.empty}")
private String stationName;
#Column(name = "hd_enabled")
private Boolean hdEnabled;
#Column(name="call_sign", nullable = false)
#NotEmpty(message = "{station.call.sign.empty}")
private String callSign;
#Column(name="user_created_timestamp")
#JsonIgnore
private LocalDateTime createdTimeStamp;
#Column(name="user_modified_timestamp")
#JsonIgnore
private LocalDateTime updatedTimestamp;
/**
* Initialises the timestamps prior to update or insertions.
*
* <p>The implementation ensures that time stamps would always reflect the time when entities
* were persisted or updated.
*/
#PrePersist
#PreUpdate
public void setTimestamps() {
LocalDateTime utcNow = LocalDateTime.now(ZoneOffset.UTC);
if (this.createdTimeStamp == null) {
this.createdTimeStamp = utcNow;
}
this.updatedTimestamp = utcNow;
if (this.hdEnabled == null) {
this.hdEnabled = Boolean.FALSE;
}
}
// Getters, Setters, Equals and HashCode functions.
}
Unit tests
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes= {App.class})
public class StationTest {
#Autowired
private Validator validator;
private Station station;
#Before
public void setUp() throws Exception {
this.station = new Station();
}
#Test
public void testValidator_allNulls() {
Set<ConstraintViolation<Station>> constraintViolations =
this.validator.validate(this.station);
MatcherAssert.assertThat(constraintViolations.isEmpty(), Is.is(false));
for (ConstraintViolation<Station> constraintViolation : constraintViolations) {
System.out.println(constraintViolation.getMessage());
}
}
}
This is my output
. . . . Rest of the stack trace omitted . . . .
2018-12-01 23:30:38.532 INFO 21297 --- [ main] com.iheartmedia.model.StationTest : Starting StationTest on Kartiks-MacBook-Pro-2.local with PID 21297 (started by krishnanand in /Users/krishnanand/projects/iheartmedia)
2018-12-01 23:30:38.533 DEBUG 21297 --- [ main] com.iheartmedia.model.StationTest : Running with Spring Boot v2.0.5.RELEASE, Spring v5.0.9.RELEASE
2018-12-01 23:30:38.539 INFO 21297 --- [ main] com.iheartmedia.model.StationTest : No active profile set, falling back to default profiles: default
2018-12-01 23:30:38.596 INFO 21297 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Refreshing org.springframework.web.context.support.GenericWebApplicationContext#6892b3b6: startup date [Sat Dec 01 23:30:38 PST 2018]; root of context hierarchy
2018-12-01 23:30:39.565 INFO 21297 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$b7d31eab] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-12-01 23:30:39.730 INFO 21297 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-12-01 23:30:39.871 INFO 21297 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-12-01 23:30:39.903 INFO 21297 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-12-01 23:30:39.917 INFO 21297 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-12-01 23:30:40.030 INFO 21297 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.17.Final}
2018-12-01 23:30:40.031 INFO 21297 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-12-01 23:30:40.066 INFO 21297 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-12-01 23:30:40.196 INFO 21297 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2018-12-01 23:30:40.652 INFO 21297 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-12-01 23:30:40.985 INFO 21297 --- [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2018-12-01 23:30:41.351 INFO 21297 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-01 23:30:41.586 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext#6892b3b6: startup date [Sat Dec 01 23:30:38 PST 2018]; root of context hierarchy
2018-12-01 23:30:41.624 WARN 21297 --- [ 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-12-01 23:30:41.658 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/iheartmedia/stations],methods=[GET]}" onto public java.util.List<com.iheartmedia.model.Station> com.iheartmedia.controller.StationController.retrieveAllStations()
2018-12-01 23:30:41.660 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/iheartmedia/station],methods=[POST]}" onto public org.springframework.http.ResponseEntity<com.iheartmedia.dto.StationMixin> com.iheartmedia.controller.StationController.createStation(com.iheartmedia.model.Station,org.springframework.validation.Errors)
2018-12-01 23:30:41.660 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/iheartmedia/station],methods=[DELETE]}" onto public org.springframework.http.ResponseEntity<com.iheartmedia.dto.StationMixin> com.iheartmedia.controller.StationController.deleteStation(com.iheartmedia.model.Station)
2018-12-01 23:30:41.663 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-12-01 23:30:41.664 INFO 21297 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-12-01 23:30:41.687 INFO 21297 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-01 23:30:41.687 INFO 21297 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-01 23:30:41.979 INFO 21297 --- [ main] com.iheartmedia.model.StationTest : Started StationTest in 3.704 seconds (JVM running for 4.431)
{station.call.sign.empty}
{station.name.empty}
{station.id.empty}
2018-12-01 22:11:10.360 INFO 18663 --- [ Thread-2] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#6892b3b6: startup date [Sat Dec 01 22:11:06 PST 2018]; root of context hierarchy
2018-12-01 22:11:10.363 INFO 18663 --- [ Thread-2] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2018-12-01 22:11:10.364 INFO 18663 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2018-12-01 22:11:10.367 INFO 18663 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Process finished with exit code 0
messages.properties Resource bundle
station.not.found=Station {0} was not found
station.id.empty=Station ID can not be empty.
station.id.format.not.valid=Station ID ${validatedValue} is not valid. Station ID should start with either W or K.
station.name.empty=Station name can not be empty.
station.call.sign.empty=Station call sign can not be empty.
Our dependency tree
I have read the following
Custom error messaging on Hibernate Validation
Custom Message Key in Hibernate validator not working with message.property
Does Spring Boot automatically resolve message keys in javax and hibernate validation annotations
but I can not still figure out what I am doing wrong.
UPDATE
Upon #Jonathan Johx's suggestion, I changed the basename of the ResourceBundleMessage to messages (Updated the code snippet as well), but I still get the error.
The issue is because the classpath: does reference to root of folder which is ConfigurationHelper class, it's not found. Try to rename file name to ValidationMessages.properties which is used by Validator and update the following line:
messageSource.setBasenames("ValidationMessages");
UPDATED
If you want to use validation messages by default then you have to create a file called:
ValidationMessages.properties
And add properties that you consider necessary.

Springboot doesn't create the database schema

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 !

Resources