DB Migration in Spring boot - java

I want to load a json file in to Database while application start up.
Let take an example:
i have a json file as below.
Person.json
{
{
"name":"Rahul",
"age":"61"
},
{
"name":"Raj",
"age":"67"
}
}
DB Table : Person
name | age
I want to store json data in DB. If i add any new object in json file it should be identified and added.
What is the best design for this. Need to use Spring Boot, Spring.

You can use a CommandLineRunner and reflect over all the classes inside of your model package and look for a .json file. If you find one, deserialize the contents and save them to a database.
See this link:
http://therealdanvega.com/blog/2017/07/05/read-json-data-spring-boot-write-database
The code to get all classes within a package can be found here:
https://dzone.com/articles/get-all-classes-within-package

Related

How to make a connection between an external mysql database and then call in for specific data queries

I am working on a springboot project and I am a total newbie in this. We are told to complete the project within a given time period and the deadline is in 3 days. I have a string which will contain the username. I am said that there will be an external database from where we have to fetch the data of that user and return that to the application. We are working on a web api.
Till now I have somehow extracted the username from the encoded data but now I am unable to proceed further. All the resources available online are related to building a repository and their own data and use that in the program but I have to use it from an external database. I don't know anything about this and is completely stuck.
The external database is a sample and includes an id , username and data. From the username we have to search the database and return all the three details as a JSON format of that user.
Well that was simple in SQL but I don't know how that can be performed from the point where I am now.
Thank You.
There is a special file called application.properties in Spring Boot, where you can define your authorization data to get connection with your remote database.
Usually, you should specify basic data:
spring.datasource.url=jdbc:mysql://url-to-your-external-db/name-of-db
spring.datasource.username=your_username
spring.datasource.password=your_pasword
After that, you could retrieve your data from database using JpaRepository for example. There is plenty of frameworks that will serialize/deserialize your Java objects/entities to JSON (Jackson for example).
Example of fetching users from a database using JpaRepository:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByFirstName(String firstName)
}
where User could be your POJO which represents a table with users in database.

Dynamic java business rule validation

I am struggling to fit below use case.
Requiremnet:Dyamic comparison tool.Input to method is a json and then map it java class and then run some validation and persist it to database along with the result of the validation.
This looks simple when your json is predefined.You can create a java class and write code to do the required validation.
My use case is to be able to handle any kind of json and then create a beam dynamically and run some rule on it on the go
Now for example
Json 1:Student info json which has information about name,class,marks.
Validation:Persist data to DB only if marks>50
Json 2:Order info json which has information about order id,price,order type.
Validation:Persist data to DB only if order type= shoe.
Things i need to do:
Step 1: create a test file that has info regarding data type of validation object and the validation condition.
(Only way i think i can pass validation rule dynamically.Like how Apache does it on log stash.
Eg: https://www.elastic.co/guide/en/logstash/current/configuration-file-structure.html)
Step 2:Pass this test file while compiling your spring boot project.
Sample text file format
input{
name:String
class:String
grade:String
}
ValidationRule{
marks>50
}
output{
//if in case you don't want to persist all the data to db.You can mention which
field to use.
}
Now with the help of this text file i am assuming that java can create a bean.Then apply business rule to it.

include_in_all setting in spring data elasticsearch

According to Elasticsearch documentation it is possible to exclude a field from _all field using include_in_all setting (set to false). I need to exclude a field from _all and I'm using spring data elasticsearch do define my mappings. I haven't found a way to do it this way.
Is this possible using spring data elasticsearch annotations?
Unfortunately, Spring Data Elasticsearch cannot do this thing. The improvement request is already a year old, but its priority is minor, so there is no hope for now:
https://jira.spring.io/browse/DATAES-226
In my last project I had to do a lot of simple searches (instead of one by "_all" fields, I used 1 search per each field), and then I united all the results. I assume that there is no nice solve for that problem by Spring Data Elasticsearch.
You can save the mapping of your type into a json file. Then you add the '"include_in_all": false' to the field you want to exclude. This should look something like this.
{
"my_type": {
"properties": {
"excludedField": {
"type": "text",
"include_in_all": false
}
}
}
}
Then you load the file using your favorite JSON reader, parse it as a string and change your mapping with the elasticsearch api .
client.admin().indices()
.preparePutMapping("my_index")
.setType("my_type")
.setSource(loadedFileString)
.get();
EDIT: I just noticed you wanted to use annotations for it. Maybe the #Field annotation has a parameter for it? I'm sorry, I have no experience with the annotations.

REST response with selective json properties from json

I have an entity like
public class Pojo{
int id;
org.json.JSONObject json;
/* other properties */
}
Now what I want to do is to send this Pojo object back as JSON BUT in a selective way so that an admin user has access to all properties and a regular user has selective access.
I can do that by using Spring JSONView and creating different views for admin and a regular user. However, the problem which i am stuck at that how can i add selective properties for admin/regular user from JSONObject? The only possible way i could think of is to create a another Pojo to map that object and then use that object in response. But I want to make sure that there is no other way to approach this.
P.S: its a spring boot application
I'm not sure if it works with JsonObject but you can give this a try. Would be interesting to know if it works with "dynamic" objects.
https://github.com/Antibrumm/jackson-antpathfilter
(I'm the creator of that project)

How to automatically map POJOs to database to create tables using NetBeans

I have wrote some POJOs in NetBeans, and want to map these entities automatically to an empty database, to be tables.
I have read the netbeans official tutorial https://netbeans.org/kb/docs/java/hibernate-java-se.html#06a
But using Hibernate Mapping File as the document says can not choose the Database Table value, compare to the pic
(https://netbeans.org/images_www/articles/70/java/hibernate-j2se/mapping-wizard.png,
The actor value will not show since my database is empty.
So what should I do if I followed the tutorial, or is there any other method to automatically create tables by POJO in NetBeans?
There is one property hibernate.hbm2ddl.auto in hibernate which create tables as per your pojo structure.
Refer this doc.
MyBatis Generator can generate POJOs of tables. Visit this site to help you get started http://code.google.com/p/mybatis/wiki/Generator
Follow this tutorial on Hibernate mapping files.
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/xml.html
I never used NetBeans but if you write mapping file by yourself then you can use an empty database.
Use SchemaExport.export. Run following code in main() method:
AnnotationConfiguration configuration = new AnnotationConfiguration();
SchemaExport schemaExport = new SchemaExport(configuration);
schemaExport.export(true, true, true, false);

Categories

Resources