I want to get data from my DB where is LocalDateTime equals to LocalDateTime in get request.
#Override
public List<Timeslot> getAllAvailable(LocalDateTime localDateTime) {
return jdbcTemplate.query("select * from timeslot where day = ?", TIMESLOT_ROW_MAPPER);
}
Timeslot table code:
CREATE TABLE "timeslot" (
"timeslot_id" serial,
"day" date NOT NULL,
"start_time" TIME NOT NULL,
"end_time" TIME NOT NULL,
"user_id" serial NOT NULL,
"is_recorded" boolean,
CONSTRAINT "timeslot_pk" PRIMARY KEY ("timeslot_id")
);
Controller code:
#GetMapping("/allAvailable")
public List<Timeslot> getAllAvailable(#RequestParam("day") #DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime day) {
return userService.allAvailable(day);
}
But when I did this request result in console is: org.postgresql.util.PSQLException: ERROR: syntax error at end of input. How do i change sql request code to fix this error? Should I use PrepareStatement or something else?
As #AndrewS mentioned, you didn't pass localDateTime value as parameter. Therefore jdbcTemplate doesn't bind ? to localDateTime.
You should use overloaded method of query and pass localDateTime as the last parameter:
jdbcTemplate.query("select * from timeslot where day = ?", TIMESLOT_ROW_MAPPER, localDateTime);
I think you are storing day as Date format in the database. and in the query you are comparing day whose type is Date with LocalDateTime type which might be wrong. first take Date from LocalDateTime then pass as method argument. For example
jdbcTemplate.query("select * from timeslot where day = ?", TIMESLOT_ROW_MAPPER, localDateTime.toLocalDate());
Related
I want to return a list of Documents that have a timestamp for a specific date. However, the timestamp also contains the time. Is there a method to filter by just the date part of the timestamp?
timestamp: 2022-10-27T11:11:07.350+00:00
Query method:
public static Query getEventByDateQuery(final String date) {
return Query
.query(
where("timestamp").......
);
}
My domain has and Date field updated, that I want to search by
#Column(name = "updated")
Date updated;
I have a Java Date object representing a day, that's passed in by my endpoint's controller.
Date day;
and a crudrepository representing my data
public interface DataRepository extends CrudRepository<Data, Long> {
List<Data> findByLastUpdatedInDate(Date date);
}
Obviously the above method doesn't work, but is there something similar? Or am I going to have to do a find between then manually search for the last entry?
Edit: Here's how I get day; dateString is passed in by the controller.
SimpleDateFormat dateFormatIn = new SimpleDateFormat("yyyy-MM-dd");
Date day = dateFormatIn.parse(dateString);
You're almost there. The slight tweak would be this if I read the documentation correctly:
Data data = dataRepository.findTopByUpdatedBetweenOrderByUpdatedDesc(start, stop);
Source: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result
You can annotatw your method with #Query annotation and write HQL query
#Query("select d from Data d where d.updated= :date")
List<Data> findByLastUpdatedInDate(#Param("date") Date date);
I'm hoping someone finds something more elegant, but for now what I'm using is
List<Data> findByUpdatedBetweenOrderByUpdatedDesc(Date start, Date stop);
And converting day with
Date start = new Date(day.getTime());
Date stop = new Date(day.getTime() + 86400000L);
to get my entry with
Data data = dataRepository.findByUpdatedBetweenOrderByUpdatedDesc(start, stop).get(0);
I am new to java GUI
I have a form for simple data input that saved to mySQL. Among the textboxes I have defined is dateOfBirth.
In mySQL, the dateOfBirth column is type DATE.
When I attempt to save my record, I get incompatible conversions. How Do I handle this? The Date fields are DOR and DOB.
I tried to define a format :
DateFormat df= new SimpleDateFormat("dd/MM/yyyy");
and also changed redefined the var DOR or DOB as String:
String DOB = new String();
then when inserting into database, formatted the var like this:
df.format(DOB)
I still got the error: "Error: Cannot format given object as a Date". What to do?
String query = "INSERT INTO members (MemberID,FamilyName,BaptismName,DateOfRegistration,DateOfBirth,FatherName,MotherName,gender,MemberType,Address,Residence,City,CreatedBy)"
+"VALUES('"+memberID+"','"+familyName+"','"+baptismName+"','"+DOR+"','"+DOB+"','"+fatherName+"','"+motherName+"','"+gender+"','"+memberType+"','"+address+"','"+residence+"','"+city+"','"+operator+"')";
con.UpDate(query);
First of all i would not use that query for the insert. You should use a prepared statement. It's safer against sql injection.
PreparedStatement ps =
connection.prepareStatement("INSERT INTO members (MemberID,FamilyName,BaptismName,DateOfRegistration,DateOfBirth,FatherName,MotherName,gender,MemberType,Address,Residence,City,CreatedBy) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, memberID); //or the correct type if not String
ps.setString(2, familyName);
ps.setString(3,baptismName);
DateFormat df= new SimpleDateFormat("dd/MM/yyyy"); //this the the format in which the user enters the date in the textbox. they have to input a string like 12/31/2014
java.util.Date date=df.parse(DOB); //DateFormat class has a method called parse which returns a java.util.Date object
ps.setDate(4, new java.sql.Date(date.getTime()));
//PreparedStatement class method setDate takes 2 parameters
//first is the index of the parameter in the prepared statement, and the second
//is java.sql.Date object.
//use constructor of java.sql.Date which takes a long parameter to create this object
//java.util.Date getTime() method returns a long value representing the date object
//so basically you convert string DOB to java.Util.Date,
//then convert java.Util.Date object to java.sql.Date needed by prepared statement
...
ps.executeUpdate();
I've the following hql query:
Query query = session.createQuery("from Appointments where datetime < :now");
query.setDate("now", new Date());
listApps = query.list();
It return only the records before today (yesterday, 2 days ago and so on)
But not the record of today before than this time.
The datetime into the database is of type DateTime, so it contains both date and time.
Why is this query not returning the record of today before than the current time?
This is the way datetime is defined inside my entity:
#Temporal(TemporalType.TIMESTAMP)
private Date datetime;
Change from
query.setDate("now", new Date());
to
query.setTimestamp("now", new Date());
or to:
query.setParameter("now", new Date());
Bind the date (time is truncated) of a given Date object to a named query parameter.
public Query setDate(String name, Date date);
Bind the date and the time of a given Date object to a named query parameter.
public Query setTimestamp(String name, Date date);
I am using the criteria query as follows:I want to fetch the reservations after the time and date I have passed.but now i am getting the reservation before the time which i have passed for the same date.Please help..
#GET
#Path("/getReservationByUserIdAndTypeAndDateTime/{userid}/{type}/{date}/{time}")
public List<Reservation> getReservationByAndUserIdAndTypeAndDateTime(#PathParam("userid") int uid, #PathParam("type") int tid,#PathParam("date") Date date,#PathParam("time") Time time) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Reservation> criteria = builder.createQuery(Reservation.class);
Root<Reservation> r = criteria.from(Reservation.class);
TypedQuery<Reservation> query = em.createQuery(
criteria.select(r).where(new Predicate[]{
builder.equal(r.get(Reservation_.usersId), uid),
builder.equal(r.get(Reservation_.reservationsType), tid),
builder.greaterThanOrEqualTo(builder.concat(r.get(Reservation_.date), " "+r.get(Reservation_.time)), date.toString()+" "+time.toString())}));
return query.getResultList();
}
Comparing dates and times formatted as string is not advisable, results can depend on the format. It would be better having a unique Date field in the Reservation class:
#Temporal(TIMESTAMP) Date date;
and using date comparison in the query:
builder.greaterThanOrEqualTo(r.get(Reservation_.date), date)
This way the time parameter in the getReservationByAndUserIdAndTypeAndDateTime method can be omitted, since the date parameter would hold both date and time.