Find all records from database where date is from - to - spring

How can I return all entities in a list for specific date range or for current month if I've only a parameter
#CreatedDate
#Column(nullable = false, updatable = false)
private Instant createdAt;
The result I would like to get is a List of this entity where the createdAt is between from to or return it for the current month. Is there a possibility to perform those actions using just the repository without #Query or not, any ideas?

You can use a #Query annotation and the SpEL support to calculate upper and lower bound for your date range.

Related

Select Datetime as Date in criteria query

I'm using JPA CriteriaBuilder to select attributes from the database. I have a specific use case that involves Conversion of datetime to date. The Projection segment of the code is as follows.
CriteriaQuery<ResponseDTO> query = cb.createQuery(ResponseDTO.class);
query.multiselect(root.get(MasterPackagesV1_.masterPackageName),
packageJoin.get(PackagesV1_.packageId),
packageJoin.get(PackagesV1_.packageName),
packageJoin.get(PackagesV1_.startSellingDate),
packageJoin.get(PackagesV1_.endSellingDate),
packageJoin.get(PackagesV1_.createdDate),
packageJoin.get(PackagesV1_.modifiedDate),
packagePaymentJoin.get(PackagePaymentPlanV1_.mrp),
packageSubscriptionJoin.get(PackageSubscriptionsV1_.packageSubscriptionId)
);
All of the date attributes are stored as datetime datatype in the MySQL database. I'm want the datetime to be formatted to date. i.e Instead of retrieving the Dates as LocalDateTime I want it to be converted to LocalDate during Instantiation.
I have made changes in the ResponseDTO class accordingly to support LocalDate. Thanks in Advance.

Query by Example Spring Data

I have domain object Person with date fields:
public class Person {
#Id
private Long id;
private Date date
Build example like this:
Person person = new Person();
person.setSomeOtherFields("some fields");
Example<Person> example = Example.of(person);
How i can create example query with date range (search entity contains date greater or equal from some date and less or equal some another date)?
The Spring Data JPA query-by-example technique uses Examples and ExampleMatchers to convert entity instances into the underlying query. The current official documentation clarifies that only exact matching is available for non-string attributes. Since your requirement involves a java.util.Date field, you can only have exact matching with the query-by-example technique.
You could write your own ExampleMatcher that returns query clauses according to your needs.

spring crud repository find top n Items by field A and field B in list order by field C

I have in a Spring Repo something like this:
findTop10ItemsByCategIdInOrderByInsertDateDesc(List ids)
I want the first 10 items where category id in list of ids ordered by insert date.
Another similar query:
findTop10ItemsByDomainIdAndCategIdInOrderByInsertDateDesc(List ids, #Param Integer domainId)
Here I want that the domain id is equal to the given param and the categId to be in given list.
I managed to resolve it using #Query but I wonder if there is an one liner for the above queries.
thanks
EDIT
The top works fine. Initially I had findTop10ItemsByDomainIdAndCategIdOrderByInsertDateDesc. Now I want the results from a list of category ids. That's the new requirement.
SECOND EDIT
My query works for find the set o results where domain id is equal to a given param and categ id is contained in a given list. BUT I found out that HQL doesn't support a setMaxResult kind of thing as top or limit.
#Query("select i from Items i where i.domainId = :domainId and i.categId in :categoryIds order by i.insertDate desc")
The params for this method were (#Param("domainid") Integer domainid,List<Integer> categoryIds) but it seams that I'm alowed to use either #Param annotation to each parameter or no #Param at all ( except for Pageable return; not my case )
I still don't know how to achieve this think:
extract top n elements where field a eq to param, field b in set of param, ordered by another field.
ps: sorry for tags but there is no spring-crudrepository :)
The method to resolve your problem is:
List<MyClass> findTop10ByDomainIdAndCategIdInOrderByInsertDateDesc(Long domainId, List<Long> ids);
Top10 limits the results to first 10.
ByDomainId limits results to those that have passed domainId.
And adds another constraint.
CategIdIn limits results to those entries that have categId in the passed List.
OrderByInsertDateDesc orders results descending by insert date before limiting to TOP10.
I have tested this query on the following example:
List<User> findTop10ByEmailAndPropInOrderByIdDesc(String email, List<Long> props);
Where User is:
private Long id;
private String username;
private String password;
private String email;
private Long prop;
Currently I would recommend using LocalDate or LocalDateTime for storing dates using Spring Data JPA.

set Oracle Current Timestamp to JPA entity

I Have simple question,
I want to set Oracle CURRENT_TIMESTAMP to my JPA entity, I do not want Java to send value.
I tried below but did not work.
#Column(name="TMSP", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP", nullable=false)
private Timestamp tmsp;
its either inserting null or date I set in java but not the DB date.
You can use
updatable= false
#Column(name="TMSP", updatable= false, columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP", nullable=false)
private Timestamp tmsp;

Oracle "TIMESTAMP WITH TIMEZONE" Java type mapping issue with raw sql query

I am using an Oracle 11.2 database with column types "TIMESTAMP WITH TIMEZONE" to store time relevant information. I can't change it because it is used by an existing system.
The Java application uses ojdbc7 (v12.1.0.2) + hibernate as JPA provider.
I simplified the following example for easer understanding!
There is an entity "Product" which maps "TIMESTAMP WITH TIMEZONE" columns to java.util.Calendar
#Entity
#Table(name = "PRODUCT")
public class Product {
#Id
#Column(name = "ID")
private String id;
#Column(name = "START_DATE", columnDefinition = "TIMESTAMP WITH TIME ZONE")
private Calendar startDate;
....
}
If I load it through a HQL query it works fine.
1. Issue
If I use a raw sql query:
SELECT * FROM PRODUCT where id='123456';
I get the following exception:
org.hibernate.MappingException: No Dialect mapping for JDBC type: -101
The sql query is a lot more complex I just used a very simple example here. So I can not simply convert it to an HQL query.
2. Issue
If I persist a new product with a start date having a time zone like AEDT. E.g.
2014-01-01 12:00:00 AEDT
it get saved in the database as
01-JAN-14 01.00.00.000000000 UTC
If I query it again from the Java application the Calendar object has the time in UTC as shown above and not the time in AEDT. It is not just a display issue.
The conversion from AEDT to UTC is correct, but the problem is that the information is lost that it was inserted with timezone AEDT.
Is there a way to prevent this? Why is this happening anyway? I searched a lot today, but could not find a good hint.
You can solve the first issue the following way:
First, you need to unwrap the Query implementation. You said that you were using JPA + Hibernate, so:
Query jpaQuery = entityManager.createNativeQuery("select, t.int_c, t.str_c, t.timestamp_c from table t");
SQLQuery hibernateQuery = jpaQuery.unwrap(SQLQuery.class);
(org.hibernate.SQLQuery.class is the wrapped class)
Second, you have to set the type for ALL the columns that you want to retrieve:
hibernateQuery.addScalar("int_c", IntegerType.INSTANCE);
hibernateQuery.addScalar("str_c", StringType.INSTANCE);
hibernateQuery.addScalar("timestamp_c", TimestampType.INSTANCE);
Third, just make the query using the original JPA Query instance
List<Object[]> results = jpaQuery.getResultList();

Resources