i have a named query where I want to fetch all records where year and month of a parameter match the database entry:
#NamedQuery(
name = entries.queryX,
query = "SELECT DISTINCT t from entries t " +
"where MONTH(t.myMonth) = :month " +
"and YEAR(t.myMonth) = :year "
)
The value "myMonth" in table entries is a YearMonth:
#Column(name = "MY_MONTH", precision = 7)
private YearMonth myMonth;
I set the query parameters as follows:
query.setParameter("month", date.get(Calendar.MONTH) + 1);
query.setParameter("year", date.get(Calendar.YEAR));
However, this approach does not work... Is there any other way to implement what I want to search for?
Related
#Query(value =
"SELECT * " +
"WHERE (type REGEXP ?1) " +
"AND status= ?2 " +
"AND date(createdAt)..." +
"ORDER BY id DESC " +
"LIMIT ?4",
nativeQuery = true)
Optional<List<Item>> findLatest(String type, String status, String date, int limit);
I have this query where I'd like to filter by createdAt, only if the date value from the parameter is not null.
If String date = null, the query should not consider the AND date(createdAt)...
However if String date = "today" the query should include something like AND date(createdAt) = CURRENT_DATE
How can I achieve this?
Simplified you can make
If you have more choice you need case when
The idea is when the condition is not met, we let the and part always be true
so that the where calsue is true if all the other conditions are met
SELECT * FROM
A
WHERE
status= 72
AND IF( date = "today" , date(createdAt), current_date) = current_date
The way we usually handle this is by adding a logical check to the WHERE clause which allows a null date.
#Query(value = "SELECT * " +
// ...
"WHERE (type REGEXP ?1) AND " +
" status = ?2 AND " +
" (DATE(createdAt) = ?3 OR ?3 IS NULL) " +
"ORDER BY id DESC " +
nativeQuery = true)
Optional<List<Item>> findLatest(String type, String status, String date);
Note that it is not possible to bind parameters to the LIMIT clause, therefore I have removed it. Instead, you should use Spring's pagination API.
In the code below using java, I am trying to get data from mysql between two choosed dates and load it into table jTable1 but the problem is when I run the data loads correctly but not until the second date.
For example, if first date is 2020-1-1 and second date is 2020-1-31 the data loads from the day of 1 to the day of 30 not until the day of 31. The last day is missing! And if I choose dates from 2020-01-01 to 2020-02-01 it loads from 2020-01-01 to 2020-01-31.
java.sql.Timestamp timestamp = new java.sql.Timestamp(jDateChooser5.getDate().getTime());
java.sql.Timestamp timestamp2 = new java.sql.Timestamp(jDateChooser6.getDate().getTime());
String sql2 = "SELECT sum(`msareffishmarket`.`Amount` ) FROM `manfz`.`msareffishmarket` \n"
+ "Where `msareffishmarket`.`place` = 'محل الأسماك' And ( `msareffishmarket`.`MsarefDate` between '" + timestamp + "' And '" + timestamp2 + "' ) "
+ " group by DATE(`msareffishmarket`.`MsarefDate`)";
stm2 = conn.prepareStatement(sql2);
rs2 = stm2.executeQuery(sql2);
// JOptionPane.showMessageDialog(this, rs.getDouble(4));
jTable3.setModel(DbUtils.resultSetToTableModel(rs2));
You are using your prepared statement incorrectly (though you are correct to think to use one). Consider this version of your code:
String sql = "SELECT MsarefDate, SUM(Amount) AS total FROM manfz.msareffishmarket ";
sql += "WHERE place = 'محل الأسماك' AND MsarefDate BETWEEN ? AND ? GROUP BY MsarefDate";
stm2 = conn.prepareStatement(sql);
stm2.setTimestamp(1, timestamp);
stm2.setTimestamp(2, timestamp2);
rs2 = stm2.executeQuery(); // do not pass the query string here
Edit:
Per the correct observations of #mangusta (see below), you should be using a date/timestamp range to search for your records. Assuming you wanted all records from January 2020, you should be using:
WHERE MsarefDate >= '2020-01-01' AND MsarefDate < '2020-02-01'
Is it possible for MyBatis select query to read variable value for Select and Group By commands? If it is possible so how should I put the aggregationKeys variable inside that places? (Look into the code):
#Select({"SELECT #{aggregationKeys}, SUM(value) " +
"FROM usage_counter WHERE " + /*zrobic mape i pociagnac to tak, ze: (#{zmyslona wartosc} IS NULL OR api_consumer) itd*/
"(#{apiConsumerIds} IS NULL OR #{apiConsumerIds} like '%,'||api_consumer||',%' ) AND " +
"(#{serviceIds} IS NULL OR #{serviceIds} like '%,'||service||',%' ) AND " +
"(#{rateplanIds} IS NULL OR #{rateplanIds} like '%,'||rateplan||',%' ) AND " +
"(#{dateFrom} IS NULL OR date >= #{dateFrom} ) AND " +
"(#{dateTo} IS NULL OR date <= #{dateTo} ) AND " +
"(#{statuses} IS NULL OR #{statuses} like '%,'||counter_status||',%' ) " +
"GROUP BY ||#{aggregationKeys}||"})
#Results({
#Result(property = "date", column = "date"),
#Result(property = "apiConsumerId", column = "api_consumer"),
#Result(property = "serviceId", column = "service"),
#Result(property = "value", column = "value")
})
List<AggregatedUsage> getAggregatedUsageCounters(#Param("aggregationKeys") String aggregationKeys, #Param("dateFrom") Date dateFrom, #Param("dateTo") Date dateTo, #Param("apiConsumerIds") String apiConsumerIds, #Param("serviceIds") String serviceIds, #Param("statuses") String statuses);
Edit: Or is it possible to do grouping by in Java streams by two or more values (max 4 in this particular case)?
Second Edit: - ok it is possible but I it makes stream very complicated and I think uneffective.
I would like to parse an input date in java, and then use it in a query as a condition in a select in oracle database.
String date = "2013.11.05";
Date checkDate = new SimpleDateFormat("yyyy.MM.dd").parse(date);
String qString =
"SELECT DISTINCT T " +
"FROM T5PFArfolyamArch T " +
"WHERE T.arfTipus = :vcRateKod AND T.arfErvkezd = :checkDate AND T.araValid IN ('I','M')";
Query query = entityManager.createQuery(qString);
query.setParameter("vcRateKod", tipus);
query.setParameter("checkDate", checkDate);
But it gives 0 result, like the date is not equal or right format to select anything.
try this
query.setParameter("checkDate", checkDate, TemporalType.DATE);
consider this hibernate field:
#Column(name="datecreated", nullable = false)
#org.hibernate.annotations.Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime dateCreated;
i want to run an hql query like this:
String query = "select ticketEvent " +
"from TicketEvent ticketEvent " +
"where ticketEvent.status = :status " +
"and ticketEvent.dateCreated > :highestTicketCommentDate " +
"and ticketEvent.ticket.id = :ticketId " +
"order by ticketEvent.id DESC";
ticketEvents = (List<TicketEvent>) entityManager.createQuery(query)
.setParameter("ticketId", ticket.getId())
.setParameter("status", TicketEvent.Status.SAVED)
.setParameter("highestTicketCommentDate", highestTicketCommentDate)
.getResultList();
here highestTicketCommentDate is also a joda DateTime. but I am getting wrong results. what is the correct way to compare hql joda datetime? any help would be appreciated.
thanks in advance