Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot JPA Database Choice

How can I start a stand-alone Spring Boot JPA application -- not via cli -- with a choice of databases to get data, e.g., localhost:5432/my_db; or 192.168.1.100:5432/our_db, or example.com:5432/their_db?

Mine currently uses the one in the application.properties file that contains:

spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/my_db
spring.datasource.username=postgres
spring.datasource.password=postgres

spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create

Thanks in advance

like image 374
Luisa Francisco Avatar asked Aug 27 '14 15:08

Luisa Francisco


People also ask

Which database is used in spring boot?

Spring Boot gives you defaults on all things. For example, the default database is H2 . Consequently, when you want to use any other database, you must define the connection attributes in the application.properties file.

How does spring boot connect to database using JPA?

If we want to use JPA with MySQL database, we need the mysql-connector-java dependency. We'll also need to define the DataSource configuration. We can do this in a @Configuration class or by using standard Spring Boot properties. Spring Boot will automatically configure a data source based on these properties.

Is Spring Data JPA better than Hibernate?

JPA uses EntityManager interface to create/read/delete operation and maintains the persistence context. Hibernate uses Session interface to create/read/delete operation and maintains the persistence context. JPA uses JPQL (Java Persistence Query Language) as Object Oriented Query language for database operations.


1 Answers

Since you probably need to configure username and password as well, I recommend creating separate application-mydatasource.properties files for each data source configuration. You will then activate the datasource you want to use based on setting the active profile. You can set the active profile either in application.properties (spring.profiles.active) or via a command line argument:

$ java -jar -Dspring.profiles.active=mydatasource demo-0.0.1-SNAPSHOT.jar

The application-mydatasource.properties will then override any properties in your application.properties. I believe you will also need to set spring.profiles= to the list of profiles available.

See Profile specific properties.

like image 71
gyoder Avatar answered Nov 16 '22 02:11

gyoder