Add Hibernate to SpringBoot project - java

I have a simple Spring Boot project (already mentioned here: Replace hsqldb with MySQL)
I would like to configure Hibernate to work with this project. In another project I used to get EntityManager like so:
#PersistenceContext(unitName = "orm-unit")
private EntityManager em;
but there I also have persistence.xml with required configuration.
In Spring Boot I don't even know where to place any configuration files.
How to make Hibernate work in this case?

Read the Spring Boot documentation. Looking over 31. Working with SQL databases you will see that you need to configure a DataSource.
DataSource configuration is controlled by external configuration
properties in spring.datasource.*. For example, you might declare the
following section in application.properties:
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
You can also configure a datasource in a #Configuration mapped class which implements EnvironmentAware.
JHipster generates a cool database configuration using HikariCP. You can check it out the sample here.
For Hibernate you can configure JPA properties.
You can set spring.jpa.hibernate.ddl-auto explicitly and the standard Hibernate property values are none, validate, update, create, create-drop. Spring Boot chooses a default value for you based on whether it thinks your database is embedded (default create-drop) or not (default none).
For example to create and drop tables you can add the following to your application.properties.
spring.jpa.hibernate.ddl-auto=create-drop
As for EntityManager when you EnableAutoConfiguration you will trigger a JpaBaseConfiguration which will create an entity manager for you.
You can also use a custom EntityManagerFactory.
To take full control of the configuration of the EntityManagerFactory,
you need to add a #Bean named ‘entityManagerFactory’. Spring Boot
auto-configuration switches off its entity manager based on the
presence of a bean of that type.
And btw you can also use a traditional persistence.xml

Related

load schema from .sql to create orm mapping in springboot

Is there any way to Load the database schema from .sql or json or textfile to create the ORM mapping with JPA/Hibernate to database in spring-boot while starting up the server.
Spring Boot enables you to use database migration tools such as Liquibase and Flyway, you can read more about that on Spring's official documentation.
Edit: From the docs
85.5 Use a Higher-level Database Migration Tool
Spring Boot supports two higher-level migration tools: Flyway and Liquibase.
85.5.1 Execute Flyway Database Migrations on Startup
To automatically run Flyway database migrations on startup, add the org.flywaydb:flyway-core to your classpath.
The migrations are scripts in the form V__.sql (with an underscore-separated version, such as ‘1’ or ‘2_1’). By default, they are in a folder called classpath:db/migration, but you can modify that location by setting spring.flyway.locations. This is a comma-separated list of one or more classpath: or filesystem: locations. For example, the following configuration would search for scripts in both the default classpath location and the /opt/migration directory:
spring.flyway.locations=classpath:db/migration,filesystem:/opt/migration
You can also add a special {vendor} placeholder to use vendor-specific scripts. Assume the following:
spring.flyway.locations=classpath:db/migration/{vendor}
Rather than using db/migration, the preceding configuration sets the folder to use according to the type of the database (such as db/migration/mysql for MySQL). The list of supported databases is available in DatabaseDriver.
FlywayProperties provides most of Flyway’s settings and a small set of additional properties that can be used to disable the migrations or switch off the location checking. If you need more control over the configuration, consider registering a FlywayConfigurationCustomizer bean.
Spring Boot calls Flyway.migrate() to perform the database migration. If you would like more control, provide a #Bean that implements FlywayMigrationStrategy.
Flyway supports SQL and Java callbacks. To use SQL-based callbacks, place the callback scripts in the classpath:db/migration folder. To use Java-based callbacks, create one or more beans that implement Callback. Any such beans are automatically registered with Flyway. They can be ordered by using #Order or by implementing Ordered. Beans that implement the deprecated FlywayCallback interface can also be detected, however they cannot be used alongside Callback beans.
By default, Flyway autowires the (#Primary) DataSource in your context and uses that for migrations. If you like to use a different DataSource, you can create one and mark its #Bean as #FlywayDataSource. If you do so and want two data sources, remember to create another one and mark it as #Primary. Alternatively, you can use Flyway’s native DataSource by setting spring.flyway.[url,user,password] in external properties. Setting either spring.flyway.url or spring.flyway.user is sufficient to cause Flyway to use its own DataSource. If any of the three properties has not be set, the value of its equivalent spring.datasource property will be used.
There is a Flyway sample so that you can see how to set things up.
You can also use Flyway to provide data for specific scenarios. For example, you can place test-specific migrations in src/test/resources and they are run only when your application starts for testing. Also, you can use profile-specific configuration to customize spring.flyway.locations so that certain migrations run only when a particular profile is active. For example, in application-dev.properties, you might specify the following setting:
spring.flyway.locations=classpath:/db/migration,classpath:/dev/db/migration
With that setup, migrations in dev/db/migration run only when the dev profile is active.
85.5.2 Execute Liquibase Database Migrations on Startup
To automatically run Liquibase database migrations on startup, add the org.liquibase:liquibase-core to your classpath.
By default, the master change log is read from db/changelog/db.changelog-master.yaml, but you can change the location by setting spring.liquibase.change-log. In addition to YAML, Liquibase also supports JSON, XML, and SQL change log formats.
By default, Liquibase autowires the (#Primary) DataSource in your context and uses that for migrations. If you need to use a different DataSource, you can create one and mark its #Bean as #LiquibaseDataSource. If you do so and you want two data sources, remember to create another one and mark it as #Primary. Alternatively, you can use Liquibase’s native DataSource by setting spring.liquibase.[url,user,password] in external properties. Setting either spring.liquibase.url or spring.liquibase.user is sufficient to cause Liquibase to use its own DataSource. If any of the three properties has not be set, the value of its equivalent spring.datasource property will be used.
See LiquibaseProperties for details about available settings such as contexts, the default schema, and others.
There is a Liquibase sample so that you can see how to set things up.
Spring also supports a database initialization on its own, the official docs are here.
Spring Boot can automatically create the schema (DDL scripts) of your DataSource and initialize it (DML scripts). It loads SQL from the standard root classpath locations: schema.sql and data.sql, respectively.

H2 schema still generated when spring.jpa.generate-ddl=false

I am using Spring Boot 2.1.3 with an H2 in memory database for testing. When I run my tests, the schema gets generated even when I specify the following property.
spring.jpa.generate-ddl=false
It seems that because Spring Boot defaults the following property when using H2
spring.jpa.hibernate.ddl-auto=create-drop
That this takes precedence over spring.jpa.generate-ddl=false
Is this a bug?
This behavior is described in the Spring Boot Features documentation in chapter 11.3.3. Creating and Dropping JPA Databases:
By default, the DDL execution (or validation) is deferred until the
ApplicationContext has started. There is also a
spring.jpa.generate-ddl flag, but it is not used if Hibernate
auto-configuration is active, because the ddl-auto settings are more
fine-grained.
Since the property spring.jpa.hibernate.ddl-auto is set by default if Hibernate is used, the flag spring.jpa.generate-ddl is ignored if Hibernate is used (at least with a H2 in-memory database)

Spring boot application with MySQL connection AND an oracle connection? (Two databases)

I have the following application.properties :
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url= ${DATASOURCE_URL}
spring.datasource.username= ${DATASOURCE_USERNAME}
spring.datasource.password= ${DATASOURCE_PASSWORD}
## Other Database
second.datasource.url="jdbc:oracle:thin:#localhost:1521:XE"
second.datasource.username=usr
second.datasource.password=password
second.datasource.driver-class-name=oracle.jdbc.OracleDriver
second.jpa.show-sql=true
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.database=default
Goal and things that currently work : The spring datasource at the top works fine. I am able to use that for all of my main needs. The second one, below it, is going to query a legacy system and get data from there.
Problem : I have no idea how to get that second datasource to work at all. I need to get it to perform a query and get it returning something. Ideally I would love to see an example of this that works. I looked at a few blog posts, and googled around, and I am clearly missing some vital information.
the above is default and spring can find it on its own. To create a different DataSource you need to setup a datasource bean somewhere, and read values from a config.
Easiest way would be to create a class with configuration annotation and define beans for both dataSources.
I'd suggest HikariDataSource, you can read more about how to set it up here: https://www.baeldung.com/hikaricp
For configuration you can use Environment by autowiring it and reading your properties from there.
environment.getProperty("second.datasource.url") for example
Check the instructions in this link: https://www.baeldung.com/spring-data-jpa-multiple-databases
1) You need to provide JPA configuration for each of your datasources with 2) independent entity packages for each of these sources and, 3) you must specify one of the data source as Primary.

How to make Spring Boot fail fast when did not found database configuration

I'm running a Spring Boot application.
When there's no application.properties file in standard config paths it is not loaded and default configuration seems to be loaded.
application.properties:
spring.datasource.url=jdbc:sqlserver:...
Because of that, Spring Boot creates empty database with scheme without data which leads to empty program output.
How can one prevent Spring Boot from loading database default configuration?
you can use something as follows exclude in #EnableAutoConfiguration annotations to exclude Datasource default configuration. Reference
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
I don't know if there is any provision to make the app fail fast.
In order to stop Spring-Boot from autoconfiguring certain features for you, you need to explicitly exclude the corresponding class from the auto-configuration config:
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
Note: using this annotation you are taking back the responsibility from Spring to setup things for you, so you need to configure your DB properly from now on.

Spring boot and flyway integration - init order

I have an EntityManager (and a DataSource) created by spring boot and i want to add flyway. but EntityManager must be created after flyway and flyway after the DataSource. do i have to create whole EntityManager manually only to add 'depends-on' or is there some simpler way?
Boot doesn't create a Hibernate SessionFactory so probably you mean a JPA EntityManager. If you create your own Flyway it will always be initialized before the Boot autoconfig beans. Is that not what you see? Maybe you need to share a project.
The problem is in the usage of spring.jpa.hibernate.ddl-auto=validate (Hibernate wants to validate the DataSource before the migrations are executed, see here). A simple workaround is to switch to spring.jpa.hibernate.ddl-auto=none.

Categories