insert data from sql file H2 database spring boot - spring-boot

I'm trying to insert data from sql file using h2 database and spring boot .
when I add the sql file into src/main/ressources, I succeeded to create the table and insert data into it.
but when I create a model class named Employee which refer to the table, I can create the tables but there is no rows inserted .
SQL file:
CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(250) NOT NULL, last_name VARCHAR(250) NOT NULL,
mail VARCHAR(250) NOT NULL, password VARCHAR(250) NOT NULL );
INSERT INTO employees (first_name, last_name, mail, password) VALUES
('Laurent', 'GINA', 'laurentgina#mail.com', 'laurent');
model:
import javax.persistence.Column; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import
javax.persistence.GenerationType; import javax.persistence.Id; import
javax.persistence.Table;
import lombok.Data;
#Data #Entity #Table(name = "employees")
public class Employee {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name="first_name")
private String first_name;
#Column(name="last_name")
private String last_name;
private String mail;
private String password;
}
application.properties
#Global configuration
spring.application.name=api
#Tomcat configuration
server.port=9000
#Log level configuration
logging.level.root=ERROR
logging.level.com.openclassrooms=INFO
logging.level.org.springframework.boot.autoconfigure.h2=INFO
logging.level.org.springframework.boot.web.embedded.tomcat=INFO
#H2 Configuration
spring.h2.console.enabled=true

There are many ways to initialize the database with spring boot:
Initialize a Database Using JPA
Initialize a Database Using Hibernate
Initialize a Database using basic SQL scripts
For your information: you should separate the schema from the data,
so you should have 2 basic scripts:
schema.sql : In this file you can put your instruction to create table.
CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY,first_name VARCHAR(250) NOT NULL, last_name VARCHAR(250) NOT NULL,mail VARCHAR(250) NOT NULL, password VARCHAR(250) NOT NULL );
data.sql : In this file you can put your instruction to insert data
INSERT INTO employees (first_name, last_name, mail, password) VALUES ('Laurent', 'GINA', 'laurentgina#mail.com', 'laurent');
if you choose to use the schema.sql : you shoud use this property spring.jpa.hibernate.ddl-auto=none.
otherwise (Hibernate) you shoud use this property spring.jpa.hibernate.ddl-auto=create-drop
For your information:
Note: spring boot version <= 2.4.x you can choose Hibernate to create the schema or use schema.sql, but you cannot do both.
Note: spring boot version >= 2.5.x if you want script-based DataSource initialization to be able to build upon the schema creation performed by Hibernate, set spring.jpa.defer-datasource-initialization to true.
Be careful it depends on which version you choose!

There are a few things that could be causing this issue.
First, make sure that your SQL file is located in the src/main/resources directory. If it is not, then the file will not be picked up by Spring Boot.
Next, check the permissions on the file. If the file is not readable by the application, then it will not be able to load the data.
Finally, make sure that the SQL file is formatted correctly. If there are any syntax errors in the file, then Spring Boot will not be able to load the data.

Related

How to populate H2 DB UUID primary key using sql file in Spring Boot

I am developing a Spring Boot-2.4 application which use Spring Data JPA and I am writing test for my CURD implementation. I have few scenarios needs to load table data with specific primary key values before my test execution. I thought of using import.sql or data.sql in which i can write native SQL queries and use those supplied primary key values. As my primary key is defined as UUID eventhough I gave valid UUID data in SQL while fetching using findById its not working.
data.sql
insert into TEST_TABLE(id,name,pass) value ('2B12245566587878779679','test','xxxxx');
Assume given UUID value is valid and I can able to insert this data in H2 and able to view.
But when in JPA try to access this same ID using findById('2B12245566587878779679') will not returning this record. Is there any correct way to load the UUID and access it using .sql file.
EDIT: Included code sample
#Entity(name="TEST_TABLE")
public class TestTable{
#Id
#GeneratedValue
private UUID id;
}
#Repository
public interface TestTableRepository extends JpaRepository<TestTable,UUID>{}
#Service
public class TestTableService {
#Autowired
TestTableRepository testTableRepository;
public UUID getTableData(UUID id){
testTableRepository.findById(id); // here passing 2B12245566587878779679
}
}
Expecting one row returned but its not returning any

How do I use Spring Data JPA(Hibernate) ORM mapping to a Oracle Tables from other Schema?

The oracle db is version 12c. I use ojdbc8 connector.
I was only granted access to an account, let's call it schema "USR". Login with USR, I can see tables of another schema, let's call it schema "ADM". There is a table "TGT_TABLE" that I want to map it with JPA inside schema ADM. And under USR console, I am able to query "select * from ADM.TGT_TABLE" to get correct result. Now I write up the Entity class as:
#Data
#Entity
#Table(name = "ADM.TGT_TABLE") // or #Table(name = "TGT_TABLE") , Neither worked
public class ApiHeaderLogs {
#Id
#Column(name = "id")
String id;
....
and my config:
spring.jpa.hibernate.ddl-auto=none
# Oracle settings
spring.datasource.url=jdbc:oracle:thin:#10.119.125.70:1540:dhtlm4
spring.datasource.username=USR
spring.datasource.password=******
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
and my test:
Optional<ApiHeaderLogsEntity> ahl = apiHeaderLogsService.findById(id);
I got error:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
....
Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
and the SQL query in console is:
select ... from adm_tgt_table where ... //#Table(name = "ADM.TGT_TABLE")
Or
select ... from tgt_table where ... //#Table(name = "TGT_TABLE")
Clearly it does not address the table ADM.TGT_TABLE.
How can I map to ADM.TGT_TABLE?
My experience was mainly on MySQL, which has no account related to schema access, and my colleague already proposed a solution using JDBC directly... which I really want to avoid, please let me know if there is a proper way to handle this, thanks
You must define explicitely the table_name and the schema in the #Table annotation
Example
#Table(name="TGT_TABLE", schema="ADM")
See the documentation in javax.persistence.Table
Ommiting the schema assumes the deafult owner of the connecting session, which leads to an error.
Neither can you pass a qualified name (ADM.TGT_TABLE) as a table name.

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement in SpringBoot with h2 and JPA

While running spring boot with h2 database and JPA i am getting below error.
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
It is caused due to below one
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE TABLE EXCHANGE_VALUE (ID INTEGER NOT NULL, CONVERSION_MULTIPLE DECIMAL(19,2), FROM[*] VARCHAR(255), PORT INTEGER NOT NULL, TO VARCHAR(255), PRIMARY KEY (ID)) "; expected "identifier"; SQL statement:
create table exchange_value (id integer not null, conversion_multiple decimal(19,2), from varchar(255), port integer not null, to varchar(255), primary key (id)) [42001-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357) ~[h2-1.4.197.jar:1.4.197]
at org.h2.message.DbException.getSyntaxError(DbException.java:217) ~[h2-1.4.197.jar:1.4.197]
My hibernate class
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Exchange_Value")
public class ExchangeValue {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String from;
private String to;
private BigDecimal conversionMultiple;
private int port;
public ExchangeValue() {
}
public ExchangeValue(String from, String to, BigDecimal conversionMultiple) {
super();
// this.id = id;
this.from = from;
this.to = to;
this.conversionMultiple = conversionMultiple;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
application.properties is below
spring.application.name=currency-exchange-service
server.port=8000
spring.jpa.hibernate.ddl-auto= create-drop
Just want to know as to what i am missing in the code tried adding spring.jpa.hibernate.ddl-auto= create-drop but it did not helped.
#shubh.. Your Entity Field names are matching with SQL reserved keywords,
So try to change the field names otherwise use name attribute with #Column Annotation (which gives alias names to the DATABASE)
#Column(name="valueFrom")
private String from;
#Column(name="valueTo")
private String to;
private BigDecimal conversionMultiple;
private int port;
Your Entity Field name from was matched with database reserved word from,
change the field name to another, or add a #Column annotation on that field.
Like:
...
#Column(name = "_from")
private String from;
...
I faced the same issue. I did the mistake in giving the schema name in mysql database.
In spring.properties -> (spring boot application)
spring.datasource.url=jdbc:mysql://localhost:3306/db_microservice
Here instead of "db_microservice" I Have given the name as "db-microservice". So don't use "-". And this solved my issue.
#ganesh045's response isnt actually true because hibernate's table creation query works like this: CREATE TABLE <your_table> 'password' for example to each of your attributes. Adding the `` to the attribute will make SQL read it NOT as reserved keyword. It also does the same when it queries for your select clauses inside JpaRepository. It will make a call such as this: SELECT 'attribute' FROM <your_table>. Your problem is most likely that you specified your schema name as kebab-case or anything which is not camelCase and snake_case. Also, with this approach you can have a table called User with attribute's username and password which actually also are MYSQL reserved keywords.
Adding to others observation, I got the same error when a column name contains hyphen.
Error
#Column(name = "COST-CENTER")
private String costCenter;
Fixed
#Column(name = "COST_CENTER")
private String costCenter;
in my problem, database name was 'user'. that's why was giving a error. I changed database name, bug fixed.

Sequence "HIBERNATE_SEQUENCE" not found; SQL statement

In my spring mvc app, i have the following object. I am trying to make a visual of data using devtool in my app.
#Entity
#Data
public class ConsultationRequest {
#Id
#GeneratedValue
private Long id;
private String name;
private String email;
private String purpose;
private String programme;
private int year;
private String language;
private String comments;
#Enumerated(EnumType.STRING)
private ConsultationStatus status;
}
Then i used the jpa to make the entity:
#Repository
public interface ConsultationRequestRepository extends JpaRepository<ConsultationRequest, Long> {
}
The problem is when i load my application, i face with 2 errors:
Unsuccessful: drop sequence hibernate_sequence
[36morg.hibernate.tool.hbm2ddl.SchemaExport Sequence "HIBERNATE_SEQUENCE" not found; SQL statement:
Then when i open the
http://localhost:8080/h2-console/
I cannot see the table.
It seems that the in the boot process, table is not made.
Update your code as below:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
As you have not specified a sequence table name, hibernate will look for a sequence table named as hibernate_sequence and use it as default.
For Oracle/Postgres, increment fields used are sequence tables.
In MySql, there are increment fields that automatically increment.
If someone is getting this error with Spring Boot testing(with H2) , we have to use following in the application.properties(or whatever profile we are using) :
spring.jpa.hibernate.ddl-auto=create-drop
Setting the following property in the properties file helped me solve the hibernate_sequence problem for hibernate 5.4v
spring:
jpa:
hibernate:
use-new-id-generator-mappings: false
Check persistence.xml
property name="hibernate.hbm2ddl.auto" value="create"
not hdm2ddl
This worked in my case.
SQL operation ERROR when start app spring-boot.
I added the setting in spring properties and solved: in the spring:jpa.hibernate.ddl-auto= create-drop to hibernate be able create or drop table automatically.
If you use a 2nd cache with liquidbase, you have to add the sequence in the changelog like this:
<changeSet author="liquibase-docs"
id="createSequence-example">
<createSequence catalogName="cat" cycle="false"
incrementBy="1" ordered="true" schemaName="public"
sequenceName="hibernate_sequence" startValue="0" />
</changeSet>
For spring-boot 2.7.x and h2 2.x you need to add MODE=LEGACY; in the database connection:
example application.yml:
spring:
datasource:
url: jdbc:h2:mem:test;MODE=LEGACY;
exemple application.properties:
spring.datasource.url=jdbc:h2:mem:test;MODE=LEGACY;
For Mysql:
the auto-increment is not added, modify ur table:
ALTER TABLE table_name MODIFY COLUMN id BIGINT AUTO_INCREMENT=1

Unable to see generated tables generated by hibernate schema export (H2 database)

I am trying to get a small app going using Spring Boot (v1.1.1.RELEASE), and H2 database. In the logging i see that the ddl is correctly generated but it i just cannot find the tables inside the H2 database.
I manually copied the ddl into a db visualizer and the sql is ok. I have no clue what i am missing here. When executing code the JPA persistence layer seems to store the data correctly as i get generated ID's back etc.. I was thinking that i made a mistake in the jdbc url, but they all point to the same file based H2 database. But this database just seems to hold no data.
The JPA object
#Entity
#Table(name = "rawdata", schema = "PUBLIC")
public class RawData {
#Id
#GeneratedValue
private Long id;
#Lob
#Column(name = "payload", nullable = false)
private String payload;
// getters and setters omitted
}
The JPARepository
#Repository
public interface RawDataRepository extends JpaRepository<RawData, Long> {
}
Application properties
spring.datasource.url=jdbc:h2:file:/home/username/dev-db
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
Logging info
org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
Hibernate: drop table PUBLIC.rawdata if exists
Hibernate: create table PUBLIC.rawdata (id bigint generated by default as identity, payload clob not null, primary key (id))
org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
Test code
#Autowired
private RawDataRepository repository;
repository.saveAndFlush(new RawData("test"));
System.out.println(repository.count());
So saving a JPA object actually seems to persist the object (the count increases etc) but the data and table structure do not appear in the database. I see that the modified date changes of the database when persisting an object but i seem unable to view the data with for example squirrel/dbvisualizer etc.. Any hints or tips?
The problem is that when the application is shutdown, Hibernate will drop the entire schema, because you have configured spring.jpa.hibernate.ddl-auto=create-drop.
If you change your configuration to spring.jpa.hibernate.ddl-auto=create the schema will not be dropped at the end of the session and you will be able to see the tables that where created along with any data you inserted

Resources