How to Insert hashmap into database table? - java

I have a hashmap with pair.
the key in this are column-names in a table Now I want to insert them into a table say users_table,
i should be able to match the key to the column names and if both are same then insert that value into table.
What I am doing is that i have to write preparedstatement with all the columns and then pass the hashmap values as parameter using setter methods of preparedsatatement.
For doing this i need to know all the columns of table and this would be tedious work as there would be no. columns and this step would be repeated to no.of tables.
tell me Any idea of doing this, Thanks in Advance

First off, use a LinkedHashMap to preserve the order of the columns. This will make a difference when iterating over the map to assign column names and then values.
I'm not entirely sure what you're asking, but you're hinting at what is called Object Relational Mapping (ORM). Simply put, it's a way to map database tables to plain old Java objects (POJO). Though there's a lot more to it than that.
If you're interested in representing your database tables as objects, you should look into Hibernate, which is a popular Java ORM API.
Otherwise, create and keep to a standard that is uniform across both your database and your Java project and you'll be fine.
Edit:
If I understand your question a little more, you're having issues with knowing the names of the columns? This is something you have to know, there's not going to be an easy, dynamic, or efficient way of getting that information.
One example of setting that information is storing the column names in a String array of a class that represents your table. You can then access the array and iterate over it when saving to a database.
And finally, if you feel like doing some reading, check out my answer (Store nested Pojo Objects as individuall Objects in Database). I go quite in-depth on how I manage Database to Java and vice versa.

Related

Is it possible to refer/use to ANOTHER mapper/datasource from a myBatis mapper?

I am trying to figure out (and so far it seems I am out of luck), if it possible to refer (for association, for example) to a nested select from a different mapper/datasource ? Or may be some HashMap, which I could prepare manually beforehand..
What am I trying to achieve is basically the following:
say we have a database ONE, which has a table with a list of items. Every item has a field like "external_id"
we have also a database TWO, which is on different host and/or of a different driver type, which has a table with id; name pairs
And I would like to return a Mapped type which would contain fields from BOTH databases ONE and TWO.
Any ideas? So far I can only suggest constructing 2 POJOs independently, one with a returned ResultSet from db ONE and another with a list of id/name-pairs from db TWO and building the resulting object "by hands". But this is so boring...

Java Copying tables to another schema

I have a place where I store tables.
In this place I have a table. Lets' name it Table A. All columns in table A columns are varchars.
I want to create a process that will go through every table and create a new table in a different place in the database.
However this table has to have the right datatypes instead of varchars.
So if my column in table A is a column with the values 1234, I want to create a field that will be an INT an not a varchar.
I don't have any idea how to do it in java. Could somebody point me in the right direction on what things I would have to learn and if it is too difficult
Thanks
As I see it, your problem has a few parts:
EASY - Getting the existing table information. You'll have to get the DatabaseMetaData from your jdbc connection. Documentation on that class is here, and Google is your friend as to how to get that Object in the first place. (Hint: this question should get you most of the way )
MEDIUM - Figuring out what data type your data really is. If you try to narrow it down to just a few simple types like Integer, String, and dates, this might not actually be that hard. You'll just need to select a few rows for each column (where that column isn't null), and then try and parse it into different types. If it succeeds, it probably is that type. If it throws an Exception, then it's not. Integer.parseInt(), LocalDateTimeFormatter, etc. are the things you'll be using.
If you want to get table meta data, then just do a "SELECT * FROM < TABLE >" and the ResultSetMetaData will have all the information you'll need to keep going.
VERY HARD - Creating tables using the new, appropriate data types. This is hard not because of the stuff that's been mentioned so far, but because we haven't yet talked about foreign keys, indexes, and all that other good stuff. Mapping all those things programmatically will be a very hard problem. Therefore, I recommend NOT trying to program this part. Instead, have your script output the mapping of old datatypes to new datatypes for each table. Then you can go into your SQL mananger and get the SQL script to generate that table. Almost every SQL database management tool can generate the creation script for a table. Edit that script with your new datatypes, give it a new name, and run it.

Lookup Data in Java

I am writing an application that needs to look up data from a table (20x200) for calculation inputs. The table is filled with constants (i.e. I do not need to write to the table). I am still a novice programmer and have not had a lot of experience with databases, and so prior to proceeding I would like to know the best way to achieve this.
I had intended to place the data in an array and simply perform the lookup with 2 loops (one row look up and one column lookup) however I feel this is very inefficient. Is it worth looking into A database such as SQLite? or is that overkill for what is a relatively small data set with no requirement for editing?
As often, the answer is: It depends.
Do you need some advanced querying, like the sum of all values in the x column for which the value in the y column is greater then 23. If so a in memory SQL database comes in handy. Otherwise it would just be overkill.
Assuming the database is out of the discussion, the next questions are: Do you need single values, complete (or large parts of) columns or rows? And what are the natural "names" of your columns and rows.
Here are some options:
"names" are continuous integers: Use a 2D array (I wouldn't use arrays very often in Java, but in a read only situation with fixed lengths everything else sounds like to much overhead. By choosing the order of the indices, i.e. rows first vs. columns first you can get complete columns/rows very easy and efficient.
"names" are not continuous, Strings or any other objects: Use a Map of Maps if you need access to complete rows or columns. If you only need single values, create a Pair type and use it a the key for the map.
1) You can use a in-memory database like H2-Datbase Engine.
For which you just need to include a jar and data retrieval will be very fast.
It can't be considered as an overhead on your application.
2) Or you can use a Map<key,Map<String,string>> for the lookup.
For the main Map, key will be your record id, and for inner Map key will be your column name.
Whether to make it static or not I leave that on you to decide.
3) You can also explore caching options like ehcache.

How to store a HashMap in a database whose values are Arrays?

I'm trying to store a HashMap that will contain Arrays as values.
When I query the database, I would like to retrieve the hashmap as a java object so that I can perform operations on it as if it were simply a hashmap within the java program.
Is this possible? Would something like Hibernate work here?
Thanks for your help!
You can use hibernate, yes, but... when modelling a database, you don't need to think of the relations as HashMaps.
Instead, think of each relation.
HashMap is key => value. In your case, the 'value' is an array list, which in a database is represented by a 1:N relationship.
So all you want is a class called 'Key' with an array of values inside it.
You can use hibernate to create 1:N mappings in a very easy way, yes. So when you get the element with a certain key, you will also get your entire array list automatically.
1:N / 1->n in hibernate is called one to many. Check this link :
http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example/

How to accomplish CRUD operations on dynamic forms?

I have followed Balusc's 1st method to create dynamic form from fields defined in database.
I can get field names and values of posted fields.
But I am confused about how to save values into database.
Should I precreate a table to hold values after creating form and
save values there manually (by forming SQL query manually)?
Should I convert name/value pairs to JSON objects
and save?
Should I create a simple table with id,name,value field and
save name/value pairs here (Like EAV Scheme)?
Or is there any way for persisting posted values into database?
Regards
It look like that you're trying to work bottom-up instead of top-down.
The dynamic form in the linked answer is intented to be reused among all existing tables without the need to manually create separate JSF CRUD forms on "hardcoded" Facelets files for every single table. You should already have a generic model available which contains information about all available columns in the particular DB table (which is Field in the linked answer). This information can be extracted dynamically and generically via JPA metadata information (how to do that in turn depends on the JPA provider used) or just via good 'ol JDBC ResultSetMetaData class once during application's startup.
If you really need to work bottom-up, then it gets trickier. Creating tables/columns during runtime is namely a very bad design (unless you intend to develop some kind of DB management tool like PhpMyAdmin or so, of course). Without the need to create tables/columns runtime, you should basically have 3 tables:
1 table which contains information about which "virtual" DB tables are all available.
1 table which contains information which columns one such "virtual" DB table has.
1 table which contains information which values one such column has.
Then you should link them together by FK relationships.

Categories

Resources