Here is my document:
#Data
#Accessors(chain = true)
#Document("Template_Schema")
public class TemplateSchema {
#Id
private String id;
private ZonedDateTime activeFrom;
private ZonedDateTime activeTo;
}
I want to set a maximum date in activeTO field and save it to mongo using a repository.
I've already tried this:
TemplateSchema schema = new TemplateSchema();
Instant maxInstant = Instant.ofEpochMilli(Long.MAX_VALUE);
schema.setActiveTo(maxInstant.atZone(ZoneOffset.UTC));
templateSchemaRepository.save(schema);
This piece of code saves the data. But the date is invalid.
What is the solution to set a maximum date?
Related
I'm developing a simple REST Controller. I'm receiving a SimpleDateFormat object in Request body. Looks like that:
2014-04-13T03:42:06-02:00
My current method now is:
#PostMapping
public ResponseEntity<Flight> addFlight(#RequestBody JSONObject object) {
Flight newFlight = new Flight(object.get("flightNumber").toString(), new
SimpleDateFormat ( object.get("departureDate").toString()));
repository.save(newFlight);
return ResponseEntity.status(HttpStatus.ACCEPTED).body(newFlight);
}
And class
#Data
#Entity
#DynamicUpdate
#NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
#RequiredArgsConstructor
#AllArgsConstructor
public class Flight {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private final String flightNumber;
private final SimpleDateFormat date;
}
Everything is compiling fine, but when I'm sending POST or GET I receive all of the data that I've passed, but SimpleDateFormat is null. How could I repair it?
I've also tried to pass Object to FlightClass and then use a converter in the class's constructor, but I've still had null.
SimpleDateFormat is a legacy class and i would recommend OffsetDateTime since your input represents ISO-8601 with offset
A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.
OffsetDateTime dateTime = OffsetDateTime.parse(object.get("departureDate").toString());
I have a very slow code here. All it does is that it colleting all rows with a specific entity column.
List<Data> slectedData = dataService.findByJobNameOrderByDateTime(selectJob.getValue().getName());
List<Data> deleteThese = slectedData.subList(firstIndex - 1, lastIndex);
for (List<Data> deleteTheseLists : Lists.partition(deleteThese, 2000)) {
dataService.deleteInBatch(deleteTheseLists);
}
Then I create a sub list and I want to delete that sublist.
But the sublist can be very large and then dataService.deleteInBatch(deleteTheseLists); takes alot of time.
The entity class Data looks like this:
#Entity
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public class Data {
// ID
#Id
#GeneratedValue
private long id;
// Made by
private String jobName;
private String calibrationName;
#Column(columnDefinition = "DATETIME(3)")
private LocalDateTime dateTime;
// Analog input
private float sa0;
private float sa1;
private float sa1d;
}
And I want to delete on dateTime. Is that possible in Spring Boot JPA?
Because I can't delete on id because the id key is not correct indexed in the database because sometimes the database takes long time to insert data, and sometimes it goes fast. So it's a very unsecure way to delete entities in JPA.
Yes you can delete by dateTime using keywords
//equals
deleteByDateTimeEquals(LocalDateTime dateTime);
// lessthan
deleteByDateTimeLessThan(LocalDateTime dateTime);
// greaterthan
deleteByDateTimeGreaterThan(LocalDateTime dateTime);
I'm using spring boot JPA for CRUD operations. I'm querying the database table with the field name created_at which is of type date.There are some rows in the table with the given date but JPA is giving zero result set. I'm using Oracle 11g
Here is my entity
import java.sql.Date;
#Entity
#Table(name="veev_json")
public class VeevJson {
#Id
#Column(name="ID")
private int id;
#Column(name="CREATED_AT")
private Date createdDate;
}
My JPA Repository
import java.util.Date;
#Repository
public interface VeevJsonRepository extends JpaRepository<VeevJson, Integer> {
public List<VeevJson> findByCreatedDate(Date date);
}
Calling the function in the service layer
Date date = new Date(); //taking current date of type java.util.Date
List<VeevJson> documents = veevJsonRepository.findByCreatedDate(date);
My DB table structure
ID NUMBER(10,0)
CREATED_AT DATE
SQL query generated by the hibernate:
select veevjson0_.ID as ID1_1_, veevjson0_.CREATED_AT as CREATED_AT2_1_, veevjson0_.JSON as JSON3_1_, veevjson0_.STATUS as STATUS4_1_ from veev_json veevjson0_ where veevjson0_.CREATED_AT=?
When using a field with type Date, you should also use the #Temporal annotation. The default value of #Temporal is TemporalType.TIMESTAMP, and your JPA implementation may get confused about dealing with a field of type java.util.Date, passing as argument of query the timestamp instead of date.
Please annotate your field as
import java.util.Date;
#Entity
#Table(name = "veev_json")
public class VeevJson {
#Id
#Column(name = "ID")
private int id;
#Temporal(TemporalType.DATE)
#Column(name = "CREATED_AT")
public Date createdDate;
...
}
Doing so will allow JPA implementation to send as queried value only the date (probably in 'YYYY-MM-dd' format) instead of timestamp or any other value.
If you prefer and your JDBC supports 4.1 version, you may exchange the java.util.Date for java8 time API types, but I guess this is out of scope here.
I have the following Java Entity:
public class Round {
private ObjectId _id;
#NotEmpty
#Getter
#Setter
#Accessors(fluent = true)
#JsonProperty("userId")
private String userId;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
#JsonDeserialize(using = LocalDateDeserializer.class)
#JsonSerialize(using = LocalDateSerializer.class)
#Getter
#Setter
#Accessors(fluent = true)
#JsonProperty("date")
private LocalDate date;
//other fields
}
When I do a POST to my Spring Boot REST web app with JSON Body:
{
"userId": "user3",
"date": "20-01-2020"
}
The date is persisted in Mongo as follows:
2020-01-20T00:00:00.000+00:00
How can I get the date to persist as simply:
20-01-2020
It's not Java problem, MongoDB uses Date format similar to JavaScript Date format.
If you want to save just dd-MM-YYYY you may want to change your column type to String.
If it's not possible then you need to rewrite your serializer to return String representation of date (and of course rewrite deserializer to parse that string into LocalDate
I am trying to query mongodb using #Query. Actually, the date is truncated hours/minutes/seconds/millis to zero (both during insert and find query). I am trying to find records for specific day in year (e.g. 2019-10-10)
I see in mongodb fields of type date and stores as 2019-10-10T00:00:00.000+00:00.
When I debug code reaching the spring's AbstractMongoQuery, I see following output:
Query: { "someField" : "bla-bla", "date" : { "$date" : 1570665600000}}, Fields: {}, Sort: {}
and no records returned back. This is to String output of Document, but I am not sure how it's actually sent to Mongo.
When I am trying to query monogdb manually with {date: ISODate('2019-10-10T00:00:00.000+00:00')} I do get results.
Using spring-boot 2.2.0.Release
See my code below:
public interface MyRepository extends CrudRepository<MyObj, String> {
#Query(value = "{'someField': ?0,'date': ?1}")
List<MyObj> findWithDate(String someField, Date date);
.........
.........
.........
.........
}
#Document(collection = "test")
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder(builderClassName = "Builder", toBuilder = true)
public class MyObj {
#Id private ObjectId id;
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
#Indexed private java.util.Date date;
#Indexed private String someField;
}
Note: initially i didn't use #DateTimeFormat(iso = DateTimeFormat.ISO.DATE) and since date always came without hours/minutes/... in mongo it looked the same as I mentioned in description of problem.
I will be grateful for any help