Serializing and deserializing prepared queries in ORMLite - java

Is there any way to serialize an ORMLite prepared query and then deserialize to restore it to the original form?
In Android passing parameters to activities or fragments must be done in serialized form. Now it seems impossible to pass prepared queries as arguments in a Bundle.
Serializing them is not a problem because there is PreparedStmt<T>.getStatement() but I have not found any way to reverse the process.
There is always the solution of putting the query in a map with a String key, passing the key as an argument and then retrieving the query using that key, but I am searching for a simpler solution.

Is there any way to serialize an ORMLite prepared query and then deserialize to restore it to the original form?
Right now the answer is no and I don't think there is any way for the code to be changed to support it. A prepared query contains points to the DAO, to the internal connection source classes, etc. so it can perform its duties. There is no easy way to serialize all that information at this time.
Serializing them is not a problem because there is PreparedStmt.getStatement() but I have not found any way to reverse the process.
By reverse the process you mean generate a PreparedStmt from the query string? You should be able to do:
GenericRawResults<T> results = dao.QueryRaw(queryString, dao.getRawRowMapper());

Related

Json files vs DB table for get value

I am trying to get value like key and value pair but i am doing it from json file and now there is another approach suggested lets do it from db tables. because if in future value change then only update the DB is Needed.
I think using json file is more good as value hardly going to change in future(rarest of rare).. although advantage of db approach is just change the db value and done...
So My point is json will be faster then DB and Using Json will reduce load on DB..as clicking UI it invoke extra call of DB..
What do you Think .. Please let me know..
This very much depends on how you are going to use these data.
Do you need to update it often?
Do you need to update by just one specific field?
Do you need to fetch records based on some specific field?
Do you need to fetch whole json or just some specific fields?
Do some parts of json reference any other tables?
Also, consider the size of those data, e.g. if the json files together may become more in size than the whole other tables, you may break db cache. From the other hand, you can always create separate database for your json files if you still need some relational database features.
So, I would anyway start with answering first 5 questions.

Serializing List<javax.persistence.Tuple> to JSON

I am working on a project using JPA (EclipseLink 2.5.2) and Jersey 2.27 running on Tomcat 8 under Java 8. Currently I retrieve results using mapped entities and also some simple lists (distinct values, key-value pairs). I have implemented server-side paging, filtering and sorting. Now I'm trying to add the ability to dynamically aggregate data sets.
I've searched on SO and other sites for the best way to serialize a list of Tuples returned from my criteria builder query. So far I haven't found anything that answers my question. I can think of three ways to do it barring some good pointers from here:
Use reflection to create the appropriate object and supply it in my query
Run through the results one at a time and write out my own JSON for each element to a StringBuffer
ArrayList<HashMap<String, Object>> where the HashMap is built using the alias and matching result then added to the list, list is serialized as normal
So if there is no "easy" way to serialize a list of tuples, which method above makes the most sense? Option 3 definitely works, but feels like a kludge to me.
Generally using Reflection in business logic does not sound good so you should eliminate first option (1.). (2.) - serialising object one by one sounds good when you want to use streaming API, in your case it is not an option. Third one (3.) looks pretty normal and it a good solution because it is generic and List<Map<String, Object>> fits extremely well to JSON specification:
JSON array - List
JSON object - Map
property - String
any JSON object - Object
You should try to convert query result on EclipseLink level. See JPA 2.0 native query results as map question where is suggested to convert query result to ResultType.Map.

is it possible to avoid array of arrays in JSON using sql query with join?

I'm not sure if it's even possible but I couldn't find any information about this (or didn't ask right question).
I write web app in Java/Spring and use my own queries (#Query annotation) in dao to get data from database. When I get data from one table everything is ok.
but when I join another table I get this:
.
My front-end guy, who gets data via JSON from me through url keep asking if I can change it so here is the question:
Is it possible to join table into one json array or it's just the way it is?
Sorry if it's a stupid question, probably I'm looking for something that doesn't even exist

Better to filter using DISTINCT in query or use java's set when parsing said query's results

Question as in title. I'm querying a table to get a pair of values, and I only want to save 1 pair of each value. Is it quicker to use: the
DISTINCT clause in PostgreSQL and put that responsibility on the DB
Use Java's Set when unwrapping the query's results into objects
Both results should result in the same thing, but is one inherently better than the other?
The less data you have to marshal, transmit, and unmarshal, the faster your operation will be. This means that, in your case, getting unique data out of the database is preferable to getting non-unique data out and deriving the unique set later.
Generally it is best to do as much of your data processing as possible in the database. That's what it's there for, after all. There is an effort/complexity threshold where it can make more sense to process data in your client code, but finding unique values is one of the simplest operations.

No value specified for parameter 1

I am using Hiberante to connect to postgres database. I am trying to insert a record into the database. I have the values for the record in a string array which I got from a csv file. This is my dao code
StringBuffer query=new StringBuffer("insert into t_wonlist values(");
for(int i=0;i<67;i++){
query.append(values[i]+",");
}
query.deleteCharAt(query.lastIndexOf(","));
query.append(");");
sessionfactory.getCurrentSession().createSQLQuery(query.toString()).executeUpdate();
System.out.println("Query executed");
sessionfactory.getCurrentSession().flush();
I am using StringBuffer, so that I can append the values into the query using a for loop.
but when I execute the query I am getting the following exception
org.postgresql.util.PSQLException: No value specified for parameter 1.
I am sure that the number of parameters is correct. Can someone help me. Thanks
You're approaching this in a bizarre and backwards manner.
The immediate problem is probably failure to escape/quote a ? in one of the input strings, so PgJDBC thinks it's a query parameter. That doesn't mean you should fix it by escaping/quoting question marks, it's a sign you're taking entirely the wrong approach.
Please read this page on SQL injection and this site.
You're using the Hibernate ORM, so you'd usually be using the JPA interface or the direct Hibernate interface to create new domain objects and persisting them. The typical approach is to new an object, then use the EntityManager.persist method (if using JPA) or the Session.save method (if using Hibernate directly) to persist the entities.
If you want to use direct JDBC instead you should be creating a JDBC PreparedStatement, setting its parameters, and then applying it. See this tutorial. Since you're loading CSV you'd usually do this in a JDBC batch, though this doesn't actually gain you much in PostgreSQL.
Better yet, since you're importing CSV you can probably just use PostgreSQL's built-in COPY command via PgJDBC's CopyManager to stream the changes efficiently into the target table.

Categories

Resources