Get all the dates from database - java

I am storing objects with timestamp in the database(Realm).
public class Met extends RealmObject{
private String name;
private int met;
private long timestamp;
}
I want to show them date wise, like grouping them by date.
Since it is a timestamp and will be different for rows of the same day, I am not able to get it to work.
This comes from the backend and I cannot change it to date.
The only idea I have is to add an extra date field, so that it would be easy to query.
Is there a way to achieve this at the query level without any extra fields?

To query by the same day, you could easily set up a query that queries between the start of the day and the start of the next day.
public class Met extends RealmObject {
private String name;
private int met;
#Index
private long timestamp;
}
And
Date startOfDay = //...get start of day
Date startOfNextDay = //... get start of next day;
RealmResults<Met> mets = realm.where(Met.class)
.greaterThanOrEqualTo(MetFields.TIMESTAMP, startOfDay.getTime())
.lessThan(MetFields.TIMESTAMP, startOfNextDay.getTime())
.findAllSorted(MetFields.TIMESTAMP, Sort.ASCENDING);

Related

UnrecognizedPropertyException for a ghost attribute in XML

I'm currently writing a program to display weather data from the MSC. I'm using Jackson 2.9.6 (as a different library didn't work on other versions) and the XML extension (also in Jackson 2.9.6) to access and display the data provided online, which is in XML format.
I'm running into problems with representing the times given from the API. My code works until it hits the month, it seems.
This is what the test date data looks like.
<dateTime name="xmlCreation" zone="UTC" UTCOffset="0">
<year>2022</year>
<month name="April">04</month>
<day name="Saturday">02</day>
<hour>20</hour>
<minute>50</minute>
<timeStamp>20220402205000</timeStamp>
<textSummary>Saturday April 02, 2022 at 20:50 UTC</textSummary>
</dateTime>
And this is what my POJO class for the data looks like.
package city_weather;
import com.fasterxml.jackson.dataformat.xml.annotation.*;
public class DateTime {
#JacksonXmlProperty(isAttribute = true)
private String name;
#JacksonXmlProperty(isAttribute = true)
private String zone;
#JacksonXmlProperty(isAttribute = true)
private String UTCOffset;
#JacksonXmlProperty(localName = "year")
private int year;
#JacksonXmlProperty(localName = "month")
private Month month;
#JacksonXmlProperty(localName = "day")
private Day day;
private int hour;
private int minute;
private String timeStamp;
private String textSummary;
}
class Month {
#JacksonXmlProperty(localName = "month")
public int month;
public String name;
}
class Day {
#JacksonXmlProperty(localName = "day")
public int day;
public String name;
}
I tried to add the tags and annotations across the code, but it didn't seem to work. Also, my first few attempts featured the month/day not as separate classes but as variables Month, Day, MonthName, and DayName. I'm not sure how I'm supposed to ignore these attributes and just carry on.
When I run my code (which is just using the XMLMapper to map the XML file to an instance of that DateTime class), it doesn't work.
Here's the error it produced :
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "" (class city.weather.Month), not marked as ignorable (2 known properties: "month", "name"])
at [Source: (File); line: 3, column: 35] (through reference chain: city.weather.DateTime["month"]->city.weather.Month[""])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:60)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:822)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1152)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1567)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:136)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2902)
at Tester.main(Tester.java:8)
This stumped me because clearly you can see that there isn't any attributes listed (just a "" field, which tells me nothing). I tried to find documentation but there wasn't much I could find.
Fixed! For this I simply added #JsonIgnoreProperties({""}) in the start of the classes Month and Day.
Using #JsonIgnoreProperties({""})
on the Month and Day classes
(as written in your own answer) surely works.
Another (and in my opinion better) way would be to annotate
the month property of class Month and the day property of class Day
with #JacksonXmlText instead of #JacksonXmlProperty(...).
By doing so these properties would actually
receive the day and month number from XML.

spring boot repository: check if Date exists

In my reservation-entity i have a column "bookingDate" --> example: "2021-05-10 12:00:00".
So in this object the date and starttime of an user-booking gets displayed.
If a user wants to book a timeslot, i want to check first if the selected timeslot is empty. So i want to query the database by date&startTime.
I tried it with https://www.baeldung.com/spring-data-jpa-query-by-date , but it didnt work. I got the errors: "The annotation #Temporal is disallowed for this location" & "#Temporal cant be used for variables"
these are the relevant classes:
Reservation.java
#Entity
public class Reservation {
#Id #GeneratedValue
private int reservationId;
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime bookingDate;
private int court = 1;
private String playerNames;
private int userIdReservation;
//getter and setters
With the method "findByBookingDate()" i want to query the database, if the selected timeslot is empty...
VerificationClass.java
public boolean validateReservation(Reservation r) {
LocalDateTime tempDate = r.getBookingDate();
if(reservationRepository.findByBookingDate(tempDate)){ // todo: + and Court
logger.getLogger().info(this.getClass().getName() + "||Booking Slot is empty -- Reservation created||");
return true;
}
logger.getLogger().info(this.getClass().getName() + "||Booking Slot is full -- Reservation failed||");
return false;
}
ReservationRepository.java
#Repository
#Repository
public interface ReservationRepository extends JpaRepository<Reservation, Integer>{
#Query("Select r from reservation r where r.booking_date = :tempDate")
boolean findByBookingDate(#Param("tempDate") LocalDateTime tempDate);
}
If I run it like this i always get an "org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'backyardcodersSpringReactApplication'" --> so the application does not successfully start up.
Im very thankful for every tip and critique!
cheers!
Not understood completely. this is just a lead maybe not a perfect solution.
You can use java.time.LocalDateTime . and annotation be like #DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME).
And the query should be like. [the query will check all the reservation for that day]
Select
from reservation_table
Where
timeSlot between ‘2021-05-10 00:00:00’ and ‘2021-05-10 23:59:59’
I copied your code in my local file. Instead of
import org.springframework.data.jpa.repository.Temporal;
I used
import javax.persistence.Temporal;
in your Reservation.java file.
Also this is my very first answer on Stackoverflow.
First of all #Temporal have three different arguments and it can be applied to the variable of type date , time and time stamp.
Usage
#Temporal(Temporal type.DATE)
private Date date;
#Temporal(Temporal type.TIMESTAMP) // INSERT BOTH DATE WITH TIME TILL MILLISECONDS
private Calendar date;
Why not just just extract the localdate from your LocalDateTime and pass it on? and extract the hour and pass it on and query 2 different columns with it.
LocalDateTime.toLocalDate()
LocalDateTime.getHour()

Mapping from java.time.MonthDay to java.sql.*

We have a case, where we require only the day and the month and thus would use the java.time.MonthDay (Javadocs) to represent that information.
We are aware that we could create our own JPA object for persistence or just use the java.sql.Date object, but that generally requires an unrequired year information.
Another way is to call the method .atYear(int) (Javadoc) (with a fictitious year) on it and receive a java.time.LocalDate (Javadoc), which can be easily converted to java.sql.Date. But this is prone to missunderstandings in the future (and also persist the year information).
Is there some "elegant"/supposed solution for this case? Or is there a replacement for SQL that supports the whole new date and time API for Persistence.
Another case would be java.time.YearMonth (Javadoc).
Thanks for reading!
Since SQL databases don't have a type compatible with MonthDay, use a VARCHAR columns, and simply use toString() and MonthDay.parse().
Or use a custom DateTimeFormatter, if you don't like the --12-03 format.
The default format will correctly sort, as a string.
here are the code snippets:
// column define:
#Column(name = "date", columnDefinition = "mediumint", nullable = false)
#Convert(converter = MonthDayIntegerAttributeConverter.class)
protected MonthDay date;
// converter define:
public class MonthDayIntegerAttributeConverter implements AttributeConverter<MonthDay, Integer> {
#Override
public Integer convertToDatabaseColumn(MonthDay attribute) {
return (attribute.getMonthValue() * 100) + attribute.getDayOfMonth();
}
#Override
public MonthDay convertToEntityAttribute(Integer dbData) {
int month = dbData / 100;
int day = dbData % 100;
return MonthDay.of(month, day);
}
}

SimpleDateFormat incompatible types

I have to build a program where administration can call onto things of a certain period (choosing a start and end date and the period would be in between those).
Deciding wether a date falls in between the period to actually show the right information I want to convert a string to a date and then to milliseconds.
My code is as follows:
public class Customer
{
// instance variables
private String Consumer;
private Order order;
private String date;
/**
* Fill in the name of the Consumer and the order number.
* Fill in the date/day in dd-MM-yyyy formate please.
*/
public Customer(String Consumer, String date, Order order)
{
// initialise instance variables
this.Consumer = Consumer;
this.order = order;
this.date = date;
}
/**
* Get the startDate
*/
public void getDate()
{
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date newDate = sdf.parse(date);
}
Now I get the error "incompatible types; You wrote a String where an int was expected.). Isn't it supposed to convert a string? Why does it expect int? The error lies on the "sdf.parse(date);" part.
Any help would be awesome.

Date calculation in Entity

I have my entity class like this
#Entity
public class CheckInstrument extends BaseEntity {
public CheckInstrument() {
}
#Column(nullable = false)
private Date currentCheck;
#Column(nullable = false)
private Long periodicity;
#Column
private Date nextCheck;
#Column
private boolean isExpired;`
(getters and setters)
My issues is
Сalculate nextCheck such as adding periodicity(month) to
currentCheck
Calculate isChecked property as comparing nextCheck with current
System Date.
I think your question is a pure date calculation problem, has nothing to do with Hibernate or jpa entity.
all codes are not written in IDE, not tested either:
Calculate nextCheck such as adding periodicity(month) to currentCheck
You may want to check the Calendar class
Calendar cal = Calendar.getInstance();
cal.setTime(currentCheck);
cal.add(Calendar.MONTH,1);
currentCheck = cal.getTime();
Calculate isChecked property as comparing nextCheck with current System Date.
java.util.Date implements Comparable, so you can compare two dates like:
int result = date1.compareTo(date2);
To your question: nextCheck.compareTo(new Date())
IMO, isExpired / overdued shouldn't be added as database field. because it is related current date. It would be better to get that flag by calculation, to make it real time. Well it is anyway up to your requirement.

Categories

Resources