Replacing certain fixed String in java - java

I have a string query which looks like this
{"query":{"bool":{"should":[{"terms":{"user.id":[#users_to_follow],"minimum_match":1}},{"terms":{"tweets":[#keywords_to_track],"minimum_match":1}}]}},"filter":{"range":{"publishedDate":{"from":#Unix_timestamp}}},"size":#sizelength}"
I am trying to replace certain strings in the query with another string using:
query.replace("#users_to_follow",usersToFollow);
query.replace("#keywords_to_track", keyworsToTrack);
query.replace("#Unix_timestamp","1325930428000" );
query.replace("#sizelength",Integer.toString(SMLApplicationProperties.ES_RESULTSET_SIZE));
However when I run this thing, it does not actually replace the given strings from query.

You need to understand that String class is immutable. Any operation on String returns a new String. You need to assign it back to query variable:
query = query.replace("#users_to_follow",usersToFollow);
query = query.replace("#keywords_to_track", keyworsToTrack);
query = query.replace("#Unix_timestamp","1325930428000" );
query = query.replace("#sizelength",Integer.toString(SMLApplicationProperties.ES_RESULTSET_SIZE));

You need to get the result of the replace operation :
query = query.replace("#users_to_follow",usersToFollow);
That's because query.replace doesn't change the string you pass, it builds and returns a new one (string in java are immutable).

You can optimize (not accepted by everybody) :
String query = query.replace("#users_to_follow",usersToFollow).replace("#keywords_to_track", keyworsToTrack).replace("#Unix_timestamp","1325930428000" ).replace("#sizelength",Integer.toString(SMLApplicationProperties.ES_RESULTSET_SIZE));

Related

Spring Data and native query with like statement

I have the following repository definition:
public interface InstructionRepository extends JpaRepositoryWithSpecification<Instruction> {
String FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY =
"SELECT * FROM instruction i WHERE i.invoice_documents_trackings like '%:trackingId%'";
#Query(value = FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY, nativeQuery = true)
List<Instruction> findByFileTrackingsContaining(#Param("trackingId") String trackingId);
}
The reason why I use native query here is because invoice_documents_trackings column represents a map serialized to json string. So basically I want to find all instructions that have particular trackingId stored in the invoice_documents_trackings map.
When I execute the method I always get 0 results despite the fact that If I execute the same query manually I get expected results.
I also tried to change the query so that it looks like:
String FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY =
"SELECT * FROM instruction i WHERE i.invoice_documents_trackings like %:trackingId%"
And this does not work either.
Would really appreciate any help, than
I think the issue is the way you're using %
String FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY =
"SELECT * FROM instruction i WHERE i.invoice_documents_trackings like CONCAT('%', :trackingId, '%')"

Retriving a single column result using Hibernate HQL

using Hibernate I have a HQL query that looks like this:
String myQuery = " SELECT code,((max(mid)/min(mid))-1)*100
FROM ExchangeRate
WHERE effectivedate >= '2017-09-01'and effectivedate <= '2017-10-22'
group by name, code order by 2 desc "
With this query i want to recive the code of ExchangeRate with biggest diffrence in given time (from 2017-09-01 to 2017-10-22). Since i only want one rate I put a limit on the query and download the result using uniqueResult() method.
Session session = CRUDSessionFactory.getSessionFactory().openSession();
Query q = session.createQuery(myQuery);
q.setMaxResults(1);
Object code = q.uniqueResult();
The problem is to receive the first column value 'code' as a string which is a varchar in my Postgress database but i can't seem to find a decent solution to do it, since there's also the second column with BigDecimal as a data type. While using debug and variables window the variable code get's the proper values which looks like this:
Variable window in debugg mode
Reffering to the object code like an array by using:
String myCode = code[0];
This obviously does not work since the variable is not an array.
EDIT:
The thing that worked for me was casting the Object type from uniqueResult() to an Object array and then using first value of that array:
Object[] code = (Object[]) q.uniqueResult();
String myCode = (String) code[0];

Design for large scale parameter validation for JPA?

I have a method that takes in a JSON and takes out the data and distributes it to various strings so that they can be set in an entity and persisted. My example below is quite simple but for my actual code I have about 20+ fields
For example see
public Projects createProject(JsonObject jsonInst) {
Projects projectInst = new Projects();
String pId = jsonInst.get("proId").getAsString();
String pName = jsonInst.get("proName").getAsString();
String pStatus = jsonInst.get("proStatus").getAsString();
String pCustId = jsonInst.get("proCustId").getAsString();
String pStartDate = jsonInst.get("proStartDate").getAsString();
...
//Set the entity data
projectInst.setProjectId(pId);
projectInst.setProjectName(pName);
...
Notice if a varible dosent have a corrosponding entry in the Json this code will break with null pointer exception. Obviously I need to validate each parameter befopre calling .getAsString()
What is the best way to do this from a readability point of view I could create 2 varibles for each parameter and check and set for example.
if(jsonInst.get("proName")){
String pName = jsonInst.get("proName").getAsString();
}
Or should I wait for it to be set
if(!pName.isEmpty()){
projectInst.setName(pName)
}
...
Which of these do you think is the best parameter to use for preventing errors.
Is there a way to handle if something is set on a large scale so that I can reduce the amount of code I have to write before I use that varible?
You can create a method that will take field name as parameter and will return json value for that field :
private String getJSONData(String field,JsonObject json){
String data=null;
if(json.has(field)){
data=json.get(field).getAsString();
}
return data;
}
you can call this method for each of your field:
String pId = getJSONData("proId",jsonInst);
By this way you can not only escape NullPointerException, but also avoid code repetition.

String array calculation

i have a string array like
String[] resultYears = {"2013/07", "2013/08", "2013/09", "2013/10", "2013/11", "2013/12", "2014/01"};
when i get this through response in my jsp,
<% String[] resultYears = (String[]) request.getAttribute("resultYears");%>
i am getting the remainders of their respective values. How can i get same as above string value?
Try this way in your JAVA Class
String[] resultYears = {"'2013/07'", "'2013/08'", "'2013/09'", "'2013/10'", "'2013/11'", "'2013/12'", "'2014/01'"};
request.setAttribute("resultYears", resultYears);
Try the strings using single quotes like this
"'2013/08'"
How about instantiating a Date object with the YYYY/MM desired and do a .getTime() on it, then pass that through the request in String value. On the far end, translate it back into a pretty, human readable format.

Creating JOOQ query dynamically

I need to create a JOOQ SELECT query dynamically based on the set of parameters. I dont know how to append it dynamically.
Please help
Thanks in advance.
jOOQ has two types of APIs to construct queries.
The DSL API that allows for creating inline SQL statements in your Java code, e.g.
create.select(T.A, T.B).from(T).where(T.X.eq(3).and(T.Y.eq(5)));
The "model" API that allows for incremental SQL building. At any time, you can access the "model" API through the getQuery() method on a DSL query object
An example of what you want to do is given in the manual here:
https://www.jooq.org/doc/latest/manual/sql-building/sql-statements/dsl-and-non-dsl/
For instance, optionally adding a join:
DSLContext create = DSL.using(configuration);
SelectQuery query = create.selectQuery();
query.addFrom(AUTHOR);
// Join books only under certain circumstances
if (join)
query.addJoin(BOOK, BOOK.AUTHOR_ID.equal(AUTHOR.ID));
Result<?> result = query.fetch();
Or, optinally adding conditions / predicates:
query.addConditions(BOOK.TITLE.like("%Java%"));
query.addConditions(BOOK.LANGUAGE_CD.eq("en"));
UPDATE: Given your comments, that's what you're looking for:
// Retrieve search strings from your user input (just an example)
String titleSearchString = userInput.get("TITLE");
String languageSearchString = userInput.get("LANGUAGE");
boolean lookingForTitles = titleSearchString != null;
boolean lookingForLanguages = languageSearchString != null;
// Add only those conditions that the user actually provided:
if (lookingForTitles)
query.addConditions(BOOK.TITLE.like("%" + titleSearchString + "%"));
else if (lookingForLanguages)
query.addConditions(BOOK.LANGUAGE_CD.eq(languageSearchString));
Note, you can also use the Field.compare(Comparator, Object) methods:
// Initialise your dynamic arguments
Field<String> field = BOOK.TITLE;
Comparator comparator = Comparator.LIKE;
String value = "%" + titleSearchString + "%";
// Pass them to the field.compare() method
query.addConditions(field.compare(comparator, value));
For more info, consider the org.jooq.SelectQuery Javadoc

Categories

Resources