How to insert data to table on spring boot application start? - spring

How can I insert data to a table on Spring Boot application start? My application is generated by JHipster. What I need to check is that if that particular data already exist in that table or not. If it doesn't I should add it.

If your application was generated by JHipster, then it should already include and be properly configured for Liquibase.
You have a few options:
You can use Liquibase's insert change to insert data.
You can put your data in a CSV file and use the loadData change to load it. Look for the loadData tag in 00000000000000_initial_schema.xml for examples.
You can use the sql change to run native SQL directly.
All three options can be combined with preconditions to make sure the data doesn't exist before trying to insert it. If you need the changeset to run every time you boot your application, you can use the runAlways="true" attribute (docs for that are on this page).

You can create a function in your service class which checks if the data already exists or not and if not then save that data.

You can implement an ApplicationRunner and use a repository to do whatever you need to do.
If the ApplicationRunner is a spring bean it is run on application startup.
For more sophisticated requirements I would try to rely on a tool like flyway that has good integration with spring boot

Related

What is the best way to maintain queries in Spring boot application?

In My Application, Using the below technologies
Spring boot 2.7.x
Cassandra
spring batch 5. x
java 11
As part of this, I need to extract data from the Cassandra database and need to write out the file
so here I need to use queries to fetch data so
just want to know what is the best way to maintain all queries at one place so any query changes come in the future, I shouldn't build the app rather just need to modify the query.
Using a repository class is necessary. If you are using JPA i recommend using a repository for each Entity class. With JDBC it is possible to create a single repository which contains all the queries. To access the query methodes i would use a service class. In this way your code is structured well and maintainable for future changes.

How to set up a connection between spring boot project and PostgresSQL DB

I created a spring boot project and I link it with my DB under PgAdmin.
I've modified the application.properties correctly and created a class named "user" and its repository "userRepository" but I don't know if this will automaticly create the user table in the DB (I used annotations) or I have to create it in PgAdmin ?
Do I need to specify any controller or webController if I want to have Crud operations ? And where does the CrudRepository exists do I need to generate it and how ?
Excuse me this my first experience with spring, I will really appreciate if you guys can help me.
Thanks in advance.
For your first question:
I don't know if this will automaticly create the user table in the DB
You have several ways how to create your tables, for example with property in application.properties file
spring.jpa.hibernate.ddl-auto = [none|validate|update|create-drop]
where none means this configuration not affect existing database
update means updating changes in database
create-drop means creating all tables from scratch according your project entities classes.
You can check this documentations for additional information
https://docs.spring.io/spring-boot/docs/1.1.0.M1/reference/html/howto-database-initialization.html
59.2 Initialize a database using Hibernate
also you can check how to initialize database with existing sql scripts files in documentation above
59.3 Initialize a database using Spring JDBC
For question: Do I need to specify any controller or webController if I want to have Crud operations ? And where does the CrudRepository exists do I need to generate it and how ?
Yes you should create controllers to handle requests and repositories to work with JPA.I also suggest check tutorial first, for example this one (first in google)
https://bezkoder.com/spring-boot-jpa-crud-rest-api/

Populate database using spring / hibernate / flyway / postgresql

I'm trying to populate my database with around 150 different values (one for each row).
So far, I've found two different ways to implement the inserts, but none of them seems to be the best way to do it.
Flyway + Postgres: One of them is to create a migration file and make use of the COPY command from postgres but to do so, I need to give superuser permissions to the user and that doesn't seem to be a good choice.
Spring boot: place a data.sql file in the classpath with a lot of inserts. If I'm not wrong I would have to write 150 insert into... statements.
In previous projects, I have used liquibase and it has a loadData command which is very convenient to do what is says it does. You just give the file, table name and that's it. You end up with your csv file values in your table rows.
Is there an alike way to do that in flyway? What is the best way to populate the database?
Actually there is a way, you can find more info on the official documentation's page
You need to add some spring boot properties too:
spring.flyway.enabled=true
spring.flyway.locations=classpath:/db/migration
spring.flyway.schemas=public
Properties details here
In my case, a use Repetables scripts by my needs but take care with the prefixes
Flyway is a direct competitor of liquidbase, so if you need to track the status of migrations, manage distributed migration (many instances of the same service start simultaneously, and only one instance should actually execute a migration), check upon startup which migration should be applied and execute only relevant migrations, and all other benefits that you have previously expected from "migration management system", then you should use Flyway rather than managing SQLs directly.
Spring boot has integrations with both Flyway and Liquidbase, so you can place your migrations in the "resources" folder, define a couple of properties and spring boot will run Flyway automatically.
For example, here you can find a tutorial of Flyway integration with spring boot.
Since flyway's migrations are SQL files- you can place there whatever you want (even plSQL I believe), it will even manage transaction per migration guaranteeing that the migration "atomicity" (all or nothing, no partial migration).
So the straightforward approach would be creating a SQL file file with 150 inserts and running it via flyway in spring or even via maven depending on your actual setup.
If you want more fine-grained control and the SQL is not flexible enough, its possible to implement Migration in Java Code. See Official Flyway Documentation

making changes to database with hibernate

so im quite new to all spring and hibernate so i used a feature in myeclipse called generate CRUD application (it uses spring and hibernate for the heart of the application and JSF for presentation objects)that im intended to make changes so that i can work with .. my question is the following .. after i made the application that works fine by the way , i discovered that there are fields and probably even tables to be added to the database(an oracle 11g instance database)..so my questions are the following:
if i create the classes and update the existing .. will it be written directly in the database?
if not is there any way to do it because i dont think a direct update in the database will be a good idea ..
thank you in advance ..
If I understand correctly, you want to know whether the database schema can be created/updated automatically from your #Entity classes, and how to enable/disable such creation. Yes, it's possible by using some property. The name of the property would depend on your project kind. For example, in a default Spring Boot application, you can have
spring.jpa.hibernate.ddl-auto: update
in application.properties. The value update above will have the schema automatically created on first run and then updated on subsequently. validate instead of update won't alter the schema, but just validate it.
This stackoverflow post lists the possible values and their behaviour.

Spring Roo #RooJpaActiveRecord parameterized the JPA table catalog

I need a why to change the JPA catalog element in my java class? We have many database environments which we need to be able to deploy our application too. Example: In your dev environment we have a database for new development, and production support. All database live on the same server so we have the following database names: am_web_dd and am_web_ps. So we need to be able to change the catalog at build time or start up time. We've thought of using Maven to do a search and replace during build but I was wondering if there is a way of doing this with a parameter?
Here is one of our #RooJpaActiceRecord statements:
#RooJpaActiveRecord(catalog = "am_web_t4", schema = "dbo", table = "user_t")
I would like to be able to make catalog a parameter. Is this possible? if not what would be the best approach?
Thank you for your time!
I know it is possible from a JPA standpoint, but I don't think you will be able to using straight Roo. This might help.
There may also be a way to use a Java Configuration object in Spring to build your JPA Entity Manager. I think that's were you want to set it.
The approach you suggest of making catalog dynamic would be suitable if you wanted to let the user choose/change the schema on demand, however, it looks like this is not your requirements, so I would steer away from this path as it more difficult than you need.
You can use spring profiles to define different database connections and use an environment variable to define which one is active. Spring profiles can be set in XML or java configuration classes.

Resources