How to search by not complete timestamp by Criteria API - java

I want to search in DB all rows with a part of Timestamp like "2014-08-12". And if there are rows like "2014-08-12 16:58:48.477" or "2014-08-12 15:58:48.477" I want to get it
I use JPA + Hibernate + Criteria API
document.setRegister_date(DateUtil.DateToSQLTimestamp("2013-08-12 16:58:48.477"));
if (register_date != null) {
predicates.add(cb.equal(DocumentsRoot.get("register_date"), register_date));
}

If you know that the format will always exclude time, you can use a range query where you can set the from as 00:00:00.001 and to as 23:59:59.999

String date = "2013-08-12";
document.setRegister_date(DateUtil.DateToSQLTimestamp(date + " 00:00:00.000"));
document.setRegister_end_date(DateUtil.DateToSQLTimestamp(date + " 23:59:59.999"));
Timestamp register_date = document.getRegister_date();
Timestamp register_end_date = document.getRegister_end_date();
predicates.add(cb.between(DocumentsRoot.get("register_date"), register_date, register_end_date));

Related

How to convert custom Mongo DB update query to Java code

I was finding on the internet how to update all the document field values with lowercase.
I luckily found a query which I modified as per my requirement and it is working correctly.
db.messages.updateMany({},
[
{
$set: {
recipientEmail: {
$toLower: '$recipientEmail'
},
senderEmail: {
$toLower: '$senderEmail'
}
}
}
],{ multi: true })
But now I am trying to convert this query into Java code, I am not able to convert it.
I again started looking into the internet, but couldn’t find any code.
So, can anyone help me convert this query to Java code so that I can use it in my Spring Boot application?
Thanks in advance.
You can use #Query annotation in your repository interface and pass your query as it is (above the method signature).
Here is an example :
#Query("{$and:["
+ " {'id': ?0},"
+ " {$or:["
+ " {'customerId': ?1},"
+ " {'specificCode': ?4}"
+ " ]},"
+ " {'beginDate' : { $gte: ?2}},"
+ " {$or:["
+ " {'endDate' : { $lte: ?2}},"
+ " {'endDate' : {$exists: false}}"
+ " ]},"
+ " {'numberOfTimesUsed': { $lt: ?3}}"
+ "]}")
You can try something like this:
Query query = new Query();
Update update = new Update();
update.set("recipientEmail", StringOperators.valueOf("recipientEmail").toUpper());
update.set("senderEmail", StringOperators.valueOf("senderEmail").toUpper());
mongoTemplate.updateMulti(query, update, Messages.class);
Since you are aggregation pipeline form of update, you can try this:
Query query = new Query();
AggregationUpdate update = AggregationUpdate.update().set("recipientEmail").toValue(StringOperators.valueOf("recipientEmail").toUpper()).set("senderEmail").toValue(StringOperators.valueOf("senderEmail").toUpper());
mongoTemplate.updateMulti(query, update, Messages.class);

Add hours and compare datetime in mongoDB query in java

I have a tricky situation to find the items in mongoDB based on datetime range.
Condition: given time is in between datetime field and datetime + 12 hours
Example:
Given time:
datetime: "2022-07-18T10:00:00"
Mongo data:
{
"id": "AC-8632-2022-07-18",
"version": "1658144238",
"departure": "2022-07-18T08:00:00"
}
I want to fetch the data based on the condition :
"2022-07-18T08:00:00" < "2022-07-18T10:00:00" < "2022-07-18T20:00:00"
Query like:
Bson query = Filters.and(
Filters.gt("departure", datetime),
Filters.lt("departure" + 12, datetime));
Any suggestions on achieving below would be helpful.

how to retrieve data from firestore based on date range?

Need to fetch all data rows from my collection("data") with my ID and date range as below
Date start = new Date(01/4/2022);
Date end = new Date(30/4/2022);
fStore.collection("data").whereEqualTo("ID", userId).where("date", ">=",start ).where("date", "<=", end).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
But its complaining using 2 where clauses
solution which helped me is using .whereGreaterThanOrEqualTo("date", "01/5/2022").whereLessThanOrEqualTo("date", "31/5/2022").

Why the Time part of LocalDateTime changes it's value after persisting it in to database using JPA?

//createdAt and lastUpdatedAt are initialised like this:
LocalDateTime createdAt = LocalDateTime.now(ZoneId.of("UTC"));
LocalDateTime lastUpdatedAt = LocalDateTime.now(ZoneId.of("UTC"));
//Rest of the code...
System.out.println(rocReviewComment.getCreatedAt().toString() + ">>>" + rocReviewComment.getLastUpdatedAt().toString());
// Initialize the database
rocReviewCommentRepository.saveAndFlush(rocReviewComment);
System.out.println(rocReviewComment.getCreatedAt().toString() + ">>>" + rocReviewComment.getLastUpdatedAt().toString());
The first print : 2021-02-22T16:16:14.755>>>2021-02-22T16:16:14.762
The second print : 2021-02-22T10:46:44.389>>>2021-02-22T10:46:44.389
You can see that the Time part is changed.

SQL "missing in or out parameter at index"

i have this code for create query and execute sql-procedure but i catch missing-exception
public String generateQuery(Integer idAccount, Long[] phoneList, Date date){
StringBuilder query=new StringBuilder();
query.append("declare arr_pn owa_util.vc_arr;\n");
query.append("begin\n");
int idx = 1;
for (Long p : phoneList)
{ query.append("arr_pn(" + idx + "):='" + String.valueOf(p) + "';\n"); idx++; }
query.append("call LOC_MAINCLIENT.set_client_relations(");
query.append("id_account_ => " + idAccount);
query.append(", phone_number_list_ => arr_pn");
query.append(", dt_ => " + date);
query.append("); end;");
return String.valueOf(query);
}
after that i get this query
declare arr_pn owa_util.vc_arr;
begin
arr_pn(1):='12345';
arr_pn(2):='678970';
arr_pn(3):='5675675';
call LOC_MAINCLIENT.set_client_relations(id_account_ => 123, phone_number_list_ => arr_pn, dt_ => Sun Mar 24 21:54:00 NOVT 2013); end;
what i did wrong?
At the moment the date string isn't quoted, so it's in valid anyway, but the colons will be interpreted by the parser as bind variable markers; specifically it'll be looking for bind variables :54 and :00.
The quick answer is to put the date string into quotes. But that date format is unlikely to match what your database (session) is expecting, so you'd need to format the date into a string it can use and provide the format as well to avoid ambiguity.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
query.append(", dt_ => to_date('" + sdf.format(date)
+ "', 'YYYY-MM-DD HH24:MI:SS')");
You also don't need the call, so get rid of that. That would produce a string like this (with added line breaks and indentation to make it a little easier to see):
declare
arr_pn owa_util.vc_arr;
begin
arr_pn(1):='12345';
arr_pn(2):='678970';
arr_pn(3):='5675675';
LOC_MAINCLIENT.set_client_relations(id_account_ => 123,
phone_number_list_ => arr_pn,
dt_ => to_date('2013-03-24 21:54:00', 'YYYY-MM-DD HH24:MI:SS'));
end;
Assuming your package procedure is declared as:
procedure set_client_relations(id_account_ number,
phone_number_list_ owa_util.vc_arr, dt_ date);
... this this should run. Whether it does what you actually want is a different matter, of course.
You may also need to do something with the time zone if the database doesn't match your locale.
The proper way to do it is to use a prepared statement, provide all the values as bind variables, and pass the correct data types - passing the date as a date rather than as a string representation. That's a little more complicated for an array but certainly do-able. You've said this is legacy code and you have to use this, but you should still investigate switching to bind variables.

Categories