Comparing LocalDate with date part of LocalDateTime in apache ignite - date

I have a certain records in ignite cache and I want to retrieve all records for current day. For this I need to compare LocalDateTime type field of cached object with Localdate object i.e LocalDate.now(). How do I write a query to do this. In oracle TODATE(date, format) does the same thing but this function is not present in H2.
cached field datetime: 2016-08-30T05:31
date instance : 2016-08-30
SQL will be like
String sql = "select * from cacheName where date='convert(datetime) to date'";
Is it possible in H2 ?

You can use custom SQL functions for this: https://ignite.apache.org/releases/mobile/org/apache/ignite/cache/query/annotations/QuerySqlFunction.html
For example, if your value class looks like this:
public class MyValue {
#QuerySqlField
private LocalDateTime time;
public MyValue(LocalDateTime time) {
this.time = time;
}
}
You can create a function like this:
public static class MyFunctions {
#QuerySqlFunction
public static String toDate(LocalDateTime time) {
return time.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
}
And provide it in the configuration like this:
cacheCfg.setSqlFunctionClasses(MyFunctions.class);
The query will look like this:
select * from MyValue where toDate(time) = '2016-08-30'

Related

JPA Projection spring boot; repository mapping entity instant to do date

I have an entity that has a date modelled as an Instant
I have an DO object that has a date modelled as a Date
when i do the conversion myself in the constructor of the DO it works:
public class DO {
private Date someTimePoint;
public DO(Instant CreatedAt) {
this.someTimePoint = Date.from(CreatedAt);
}
}
and my repo works call:
List<DO> findBySomeField(UUID someField);
Give result.
However: The DO is generated and I do not have access to it, so the constructor is actually:
public DO(Date CreatedAt) {
So the question is:
Is there a way to have the conversion from Instant to Date done on the fly by Spring using the Projection methodology?
Reading https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections
doesn't give me any clues...

java.time.LocalDate not supported in native queries by latest Spring Data/Hibernate?

Problem: Native queries with Spring Data returning dates return java.sql.Date not java.time.LocalDate, despite the setup.
Context: A new project with Spring Boot 2.0.0.M5 (the latest), Hibernate 5.2.11, Hibernate-Java8 5.2.12 (which gives support for JSR310 classes as long as it's on the classpath).
Anonymized example below (the app is not really about birthdays):
public interface BirthdayRepository<T, ID extends Serializable> extends Repository<T, ID> {
#Query(value = "select day from birthdays", nativeQuery = true)
Iterable<java.sql.Date> getBirthdays(); //the return type should ideally be java.time.LocalDate
}
In the database (SQL Server), the day field is DATE and values are like 2017-10-24.
The problem is that at runtime, the Spring Data repository (whose implementation I cannot control, or is there a way?) returns java.sql.Date not java.time.LocalDate (Clarification: the return type appears to be decided by Spring Data and remains java.sql.Date even if I change the return type to be java.time.LocalDate, which is how I started to).
Isn't there a way to get LocalDate directly? I can convert it later, but (1) that's inefficient and (2) the repository methods have to return the old date/time classes, which is something I'd like to avoid. I read the Spring Data documentation, but there's nothing about this.
EDIT: for anyone having the same question, below is the solution, the converter suggested by Jens.
public class LocalDateTypeConverter {
#Converter(autoApply = true)
public static class LocalDateConverter implements AttributeConverter<LocalDate, Date> {
#Nullable
#Override
public Date convertToDatabaseColumn(LocalDate date) {
return date == null ? null : new Date(LocalDateToDateConverter.INSTANCE.convert(date).getTime());
}
#Nullable
#Override
public LocalDate convertToEntityAttribute(Date date) {
return date == null ? null : DateToLocalDateConverter.INSTANCE.convert(date);
}
}
It looks like you found a gap in the converters. Spring Data converts out of the box between java.util.Date and java.time.LocalDate but not between java.time.LocalDate and java.sql.Date and other date and time-related types in the java.sql package.
You can create your own converter to do that. You can use Jsr310JpaConverters as a template.
Also, you might want to create a feature request and if you build a converter for your use, you might even submit a pull request.
I know this is an older question, but my solution to this problem does not require a custom converter.
public interface BirthdayRepository<T, ID extends Serializable> extends Repository<T, ID> {
#Query(value = "select cast(day as date) from birthdays", nativeQuery = true)
Iterable<java.time.LocalDate> getBirthdays();
}
The CAST tells JPQL to use available java date\time types rather than java.sql.Date

Spring data elastic search findAll with OrderBy

I am using spring data's elastic search module, but I am having troubles building a query. It is a very easy query though.
My document looks as follows:
#Document(indexName = "triber-sensor", type = "event")
public class EventDocument implements Event {
#Id
private String id;
#Field(type = FieldType.String)
private EventMode eventMode;
#Field(type = FieldType.String)
private EventSubject eventSubject;
#Field(type = FieldType.String)
private String eventId;
#Field(type = FieldType.Date)
private Date creationDate;
}
And the spring data repository looks like:
public interface EventJpaRepository extends ElasticsearchRepository<EventDocument, String> {
List<EventDocument> findAllOrderByCreationDateDesc(Pageable pageable);
}
So I am trying to get all events ordered by creationDate with the newest event first. However when I run the code I get an exception (also in STS):
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property desc found for type Date! Traversed path: EventDocument.creationDate.
So it seems that it is not picking up the 'OrderBy' part? However a query with a findBy clause (eg findByCreationDateOrderByCreationDateDesc) seems to be okay. Also a findAll without ordering works.
Does this mean that the elastic search module of spring data doesn't allow findAll with ordering?
Try adding By to method name:
findAllByOrderByCreationDateDesc

Using an Arraylist in ILOG/ODM to loop through a set of records

I have a requirement to loop through a set of records and compare the start date in each record with current date and output a message in the Action part of the rule. I am trying to find out if I can use an arraylist in ILOG/ODM rule XOM and use it in the rule to loop through the set of records.
Can you please suggest me the best way to implement this requirement.
Yes, you can use an arraylist in rule XOM, and iterate over it in the rule. Let's assume your rule project takes an instance of your XOM class as an input parameter with the verbalization 'test'. You would have something like below.
XOM:
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class Test
{
private List<Record> recordList;
public Test()
{
}
public void setRecordList(List<Record> recordList)
{
this.recordList = recordList;
}
public List<Record> getRecordList()
{
return recordList;
}
public static int compareWithCurrentDate( Date date)
{
Calendar cal = Calendar.getInstance();
cal.setTime( date);
return cal.compareTo( Calendar.getInstance());
}
}
import java.util.Date;
public class Record
{
private Date startDate;
public Record()
{
}
public void setStartDate(Date startDate)
{
this.startDate = startDate;
}
public Date getStartDate()
{
return startDate;
}
}
BOM Verbalization:
# Record
Record#concept.label = record
Record.startDate#phrase.action = set the start date of {this} to {start date}
Record.startDate#phrase.navigation = {start date} of {this}
# Test
Test#concept.label = test
Test.compareWithCurrentDate(java.util.Date)#phrase.navigation = compare {0} with current date
Test.recordList#phrase.action = set the record list of {this} to {record list}
Test.recordList#phrase.navigation = {record list} of {this}
Rule:
definitions
set 'current record' to a record in the record lists of test ;
if
compare the start date of 'current record' with current date is not 0
then
print "" ;
You can follow the instructions in the ODM Blogs on developerWorks under "iterating over input parameters" topic.
It can be found here:
Iterating over Input Parameters
Basically you are going to a virtual method for your ArrayList to retrieve an entry at particular loop index. The virtual method will cast the entry before returning it, but from there you should be able to perform any rule on that object.
Note that you cannot use ArrayList as an input parameter for Dynamic XOM but you can use Arrays for input parameter with a Java XOM.

Converting a json string to a native .net object

I need to convert a json to a native .net object using mongodb. The application is written in javascript/mvc.
One of the field is a datetime object and the toJson function in the mongodb driver formats this as: "Modified":{"$date":1319630804846}
I want to parse this json from the client using the same format, but can't find a function that does this.
In Newtonsoft.Json I used this code, but this fails because of the date field:
var jobject = JObject.parse(jsonAsString)
var myObject = jobject.ToObject<myObject>();
But with the mongoDb driver, all I can do is converting the string to a BsonDocument
var buffer = new JsonBuffer(json);
using (BsonReader reader = new JsonReader(buffer))
{
var doc = BsonDocument.ReadFrom(reader);
....
}
The BSON serialization format for DateTime is an Int64 containing the number of milliseconds since Unix Epoch. So if you were to create a DateTime of kind Utc set to jan 1 1970 and then create a TimeSpan with TotalMilliseconds set to the Int64, and add the two together you'd have the date in Utc. The same algorithm could be used in reverse as needed.
If you're using the official .NET driver, you can work with objects without going through the JSON serialization.
Check the following example of how easy this is:
class Child
{
public ObjectId id;
public string name;
public DateTime birthday;
}
class Program
{
static void Main(string[] args)
{
Child m = new Child();
m.name = "Micaiah";
m.birthday = DateTime.Parse("January 1, 2011");
Children.Insert<Child>(m);
foreach (Child kiddo in Children.FindAllAs<Child>())
{
Console.WriteLine("Kiddo: {0} {1}", kiddo.name, kiddo.birthday);
}
Console.ReadLine();
}
static MongoCollection Children
{
get
{
MongoServer s = MongoServer.Create("mongodb://localhost");
return s["demos"]["children"];
}
}
}
Here's the record as stored in MongoDB:
> db.children.findOne()
{
"_id" : ObjectId("4ea821b2dd316c1e70e34d08"),
"name" : "Micaiah",
"birthday" : ISODate("2011-01-01T06:00:00Z")
}
>
Use JSON.Net to de-serialize your Json into a JObject, and send that to MongoDB... if you have more concrete types in C#, you'll want to serialize/deserialize to/from that to JSON... then persist from your concrete object, or JObject.