How to populate h2 memory table with a Real Database Table? - java

I hope i can explain this in a proper way.
I have a Sql Server Database with serveral tables.
In my Spring - Boot application,i need to query to those tables,there are a couple of tables that wont change ever.
For example,lets suppose for simplicity it s a Book table,and i query the books in different ways,by price,by id,by ISBN ,what ever.
So first thing i thought ,it s to use Redis,but that s not good for me.Why?
Well,Redis stores the data in a key-value pair,so if i catch the entire table,then in my code when i want to do same complex query to that data (Give me the book with this ISBN),that s not possible,i will need to create different Catched methods for each operations,so the next time i ask for same data ,if exist in the cache,it wont go to query to the Database.
Thats why i though about H2 memory database,i could fill my "Book" in memory table and make all kind of operation on it,because it works like a normal database and i could query anything.
Now,comes my questiion:
I know i can load initial data into H2 pointing to some script,that s ok.
But i would like to populate my "Book" in memory database,with the same data that i already have in my SQL Server Book table.
What do you think? Is that possible?Any ideas?
Thanks in advance!!

You could implement CommandLineRunner or ApplicationRunner for data initialization
https://dzone.com/articles/spring-boot-applicationrunner-and-commandlinerunne
(Also script.sql in resources with "spring.datasource.data=script.sql" property could be used for data load)

Related

Using data from JPA queries

I am attempting to write a fairly simply program that can read from and write to a SQL-server database. I've got the writing-to part down pretty well, but am having difficulty using the JPA queries effectively. As nearly as I can tell, the only way to actually access and use data retrieved by a query is to store it in an instance or list of the appropriate entity class, like so:
Query searchQuery = em.createNamedQuery("Document.findByDocTitle");
searchQuery.setParameter("docTitle", title);
List<Document> docList = searchQuery.getResultList();
I'm sure that there must be other means of accessing the data from a query, but if so I haven't been able to find them.
This method has worked for me so far, until I needed to use data from a query across joined tables. In this case it's a m:n relationship between the "document" and "author" tables. I obviously can't store the results of a joined query in a list of document objects, so I'm not sure how to proceed.
I realize that the answer is probably something simple that I just don't know about, but I've been googling JPA stuff all day without any luck. Also, if anyone knows of a good comprehensive book or tutorial for JPA, I would appreciate being pointed in the right direction.

How to retrieve data from a table in a database and print it in a table in a GUI form in Java

I have a database with tables in it which contains information. I would like to retrieve data from the table which is on the database to the table which I have made on a GUI form. I have tried retrieving the data using system.out.print method and I get results, meaning the database connection works and recognizes the table. Only problem is I do not know how to that for tables in the code. Please keep in mind that the GUI I made, the code was generated automatically so I do not have 100% access to the code.
Your connection to the database seems to be correct, however, you cannot set your table to contain the values you need. If the diagnosis is correct, then below you will find useful information:
I do not know what are you using for tables, I will assume you are using JTable, but if you use something else, only technical details should change as the thought process should remain intact.
To get general knowledge, please read this tutorial.

Can we store records got from a query to a list in stored procedure?

I am new to stored procedure, I am using hibernate concept to retrieve data from the database. client server traffic is more so I decide to move to SP by doing simple logics in server side and return needed values to front end. Now I want to know that is there any way to store records to list, so that I can rotate the list of records in a loop and ask them to come one by one and get a single field from a record and make a process then return a value to front end like we are doing in Java? List,getter,setter and generic class to store needed entities. I am confused with this.Please advise and guide me to know well about stored procedures.
It sounds like you are wanting to use a cursor over your query results, generate a temporary table, and then select the contents of that temporary table to return from your stored procedure.
You should be able to find plenty of examples online for cursors and temporary tables.

Designing an account statement

I have a mySQl innodb database which has a couple of tables which store different kind of transactions of a user. In order to show a custom 'Account Statement', I have to fetch data from all of these tables every time a user wishes to see the Account Statement.
I am not sure what would be an optimized approach.
There are a lot of users (and the data keeps changing in real time) and I'm not sure if I should keep caching the sql queries.
Should I create views that combine the table and keep updating it whenever there is an update to the parent table?
Should I perform a join on these multiple tables each time a user requests for the account statement?
I was not able to find out if there is a standard design/practice for showing account statement (with pagination). Any suggestions?
Thank you.
I would recommend to start to create a JPA mapping of your tables and then using some "standard" provider (eg. Hibernate) to access your data. This will makes transparent access from Java to your data without thinking (too much) about views, etc.
Your scenario seems very common and is exactly what RDBMS are for. Do not hesitate for performance now, when going to start your first project (if it is not your first project, this question has no sense).

keeping the history of table in java

I need the sample program in Java for keeping the history of table if user inserted, updated and deleted on that table. Can anybody help in this?
Thanks in advance.
If you are working with Hibernate you can use Envers to solve this problem.
You have two options for this:
Let the database handle this automatically using triggers. I don't know what database you're using but all of them support triggers that you can use for this.
Write code in your program that does something similar when inserting, updating and deleting a user.
Personally, I prefer the first option. It probably requires less maintenance. There may be multiple places where you update a user, all those places need the code to update the other table. Besides, in the database you have more options for specifying required values and integrity constraints.
Well, we normally have our own history tables which (mostly) look like the original table. Since most of our tables already have the creation date, modification date and the respective users, all we need to do is copy the dataset from the live table to the history table with a creation date of now().
We're using Hibernate so this could be done in an interceptor, but there may be other options as well, e.g. some database trigger executing a script, etc.
How is this a Java question?
This should be moved in Database section.
You need to create a history table. Then create database triggers on the original table for "create or replace trigger before insert or update or delete on table for each row ...."
I think this can be achieved by creating a trigger in the sql-server.
you can create the TRIGGER as follows:
Syntax:
CREATE TRIGGER trigger_name
{BEFORE | AFTER } {INSERT | UPDATE |
DELETE } ON table_name FOR EACH ROW
triggered_statement
you'll have to create 2 triggers one for before the operation is performed and another after the operation is performed.
otherwise it can be achieved through code also but it would be a bit tedious for the code to handle in case of batch processes.
You should try using triggers. You can have a separate table (exact replica of your table of which you need to maintain history) .
This table will then be updated by trigger after every insert/update/delete on your main table.
Then you can write your java code to get these changes from the second history table.
I think you can use the redo log of your underlying database to keep track of the operation performed. Is there any particular reason to go for the program?
You could try creating say a List of the objects from the table (Assuming you have objects for the data). Which will allow you to loop through the list and compare to the current data in the table? You will then be able to see if any changes occurred.
You can even create another list with a object that contains an enumerator that gives you the action (DELETE, UPDATE, CREATE) along with the new data.
Haven't done this before, just a idea.
Like #Ashish mentioned, triggers can be used to insert into a seperate table - this is commonly referred as Audit-Trail table or audit log table.
Below are columns generally defined in such audit trail table : 'Action' (insert,update,delete) , tablename (table into which it was inserted/deleted/updated), key (primary key of that table on need basis) , timestamp (the time at which this action was done)
It is better to audit-log after the entire transaction is through. If not, in case of exception being passed back to code-side, seperate call to update audit tables will be needed. Hope this helps.
If you are talking about db tables you may use either triggers in db or add some extra code within your application - probably using aspects. If you are using JPA you may use entity listeners or perform some extra logic adding some aspect to your DAO object and apply specific aspect to all DAOs which perform CRUD on entities that needs to sustain historical data. If your DAO object is stateless bean you may use Interceptor to achive that in other case use java proxy functionality, cglib or other lib that may provide aspect functionality for you. If you are using Spring instead of EJB you may advise your DAOs within application context config file.
Triggers are not suggestable, when I stored my audit data in file else I didn't use the database...my suggestion is create table "AUDIT" and write java code with help of servlets and store the data in file or DB or another DB also ...

Categories