Hibernate method name to SQL query - OR statement - java

My entity has 2 dates - startingDate, buildingDate.
I need a query that finds all rows with either date between 2 parameter dates.
public List<Factory> findByStartingDateBetweenOrBuildingDateBetween(LocalDate from, Localdate to);
Writing such method gives me an error and I have to extend parameters by another 2 dates.
public List<Factory> findByStartingDateBetweenOrBuildingDateBetween(LocalDate from, Localdate to, LocalDate fromDate, LocalDate toDate);
Is there a way to write such method that only takes 2 parameters and assigns them to both dates in the query?

I hope the below method will works for you.
public List<Factory> findAllByStartingDateLessThanEqualAndBuildingDateGreaterThanEqual(LocalDate startingDate, LocalDate buildingDate);

Use below native query above the method, Hope this will works for you.
select * from factory where (starting_date>=:from and starting_date<=:to) or (building_date>=:from and building_date<=:to);

SELECT * FROM Table_name WHERE start_date >=:from AND start_date<=:to
by using this query you can get the list of data in between this date

try this-
native query method -
#Query(value = "select * from factory where (starting_date>= ?1 AND starting_date<= ?2) OR (building_date>= ?1 and building_date<= ?2)", nativeQuery = true)
List<Factory> findFactoryByDate(LocalDate from, Localdate to);
JPA QUERY METHOD
public List<Factory> findByStartingDateOrBuildingDateBetween(LocalDate from, Localdate to);

Set<Factory> findAllByStartingDateBetween(Date Start, Date End);

Related

How to write a JPA query to find objects between two dates?

Here's my query
#Query(value = " SELECT * FROM account.statement where `date` between ?1 and ?2")
List<Statement> findAllByDate(String startDate, String endDate);
And this is the error message I get
Caused by: org.hibernate.QueryException: unexpected char: '`' [ SELECT * FROM account.statement where `date` between ?1 and ?2]
The date is the column name. I want to retrieve a list of Statement objects between two dates. The dates in this case are LocalDate objects, like 2000-10-10. I tried using String and a LocalDate type in the parameters, still doesn't work.
I've searched everywhere, on stack overflow and baeldung. I am stuck
List<Statement> findByDateBetween(Date start, Date end);
Turns out this was the correct implementation
#Query(value = "SELECT * FROM account.statement WHERE date > ?1 AND date <= ?2",
nativeQuery = true)
List<Statement> findAllByDate(LocalDate startDate, LocalDate endDate);
Thank you my guy Thomas
You should be binding LocalDate, not String, to the placeholders:
#Query(value = " SELECT * FROM account.statement WHERE date BETWEEN ?1 and ?2")
List<Statement> findAllByDate(LocalDate startDate, LocalDate endDate);
#Query("select a from Statement a where a.startDate >= :startDate and a.endDate <= :enddate")
List<Statement> findAllByDate(
#Param("startDate") Date startDate,#Param("endDate") Date endDate);
while using #Query might solve the problem, but you can also use JpaRepository in this case
First of all you need to add JpaRepository to your repository
interface :
extends JpaRepository<Statement, Long>
use this line and replcae Date with the date column name and use the appropriate type of date:
List findByDateBetween(LocalDateTime to, LocalDateTime
from);
exemple :
#Repository
public interface StatementRepository extends JpaRepository<Statement, Long> {
//where x.startDate between ?1 and ?2
List<Statement> findByDateBetween(LocalDate to,LocalDate from);
}
for more information you can see the doc

JPA Query for fomat Date

In Data base , createdDt is storing formated like:
15-01-20 10:43:20.394000000 AM
I am passing "created" as dd-mm-yyyy
I want to take the matching date from the table(without comparing time)
#Query("SELECT p FROM ABC p WHERE ( COALESCE(:created) is null or p.createdDt = :created) order by p.createdDt desc")
List<ABC> filterABC(#Param("created") Date created);
How to parse the date within query ?
You could try to use native query using specific DBMS stuff to extract date part.
#Query(value = "SELECT * from ABC where DATE_FORMAT(createdDt, '%d-%m-%Y') = ?1", nativeQuery = true)
List<ABC> filterABC(Date created);
DATE_FORMAT is MySQL specific function. Use the appropriate date function in accordance with your DBMS

Spring Data: multiple IN's inside a query

I have the following method inside my spring jpa data interface:
List<TransactRepViewModel> findByClientIdInAndClDateBetween(List<String> clientIdList, Date startDate, Date endDate)
The problem is that I get this error due to my clientIdList having about 5000-20000 String objects inside:
ORA-01795: maximum number of expressions in a list is 1000
Is there a way to use multiple IN's inside a spring-data query and split up my list to avoid the error?
Update:
Ths is how I get my client object list:
List<ClieTabModel> clieTabModelList = clieTabModelRepository.findByCompanyId(companyViewModel.getId());
This is how I get the list of client Id's:
List<String> clientIdList = new ArrayList <>();
for (ClieTabModel clieTabModel : clieTabModelList) {
clientIdList.add(clieTabModel.getClientId());
}
You can use the following query:
#Query("select u from User u where u.id in :clientIds and :startDate=? and endDate= :endDate")
List<TransactRepViewModel> findByClientIdInAndClDateBetween(Set<String> clientIds, Date startDate, Date endDate)
As I see your ER model should look like this:
Transact >--- Client >--- Company.
So, in this case you can write follow query:
List<TransactRepViewModel> findByClientCompanyIdAndClDateBetween(String companyId, Date startDate, Date endDate)

how to parse date n java to oracle/sql query?

I have a Query like
String query = "Select * from Orders where ordername = ? and orderDate > SYSDATE - 2 ";
i will pass **orderName** and lastDate from UI or some constant ("20-9-2016").
orderDate=SYSDATE - 2 --> instead of "2" i will send lastDate.
Is it correct? SYSDATE oracle function and "2" before constant. now "2" can be user input.
How to write a query in java
String query = "Select * from Orders where ordername = ? and orderDate > SYSDATE - ? ";
Is above query correct ? how to write query
public class CheckOrders extends MappingSqlQuery<Object>{
public PendingOrderExists() {
super(dataSource, queryConfig
.getProperty("query"));
super.declareParameter(new SqlParameter("ORDERNAME", Types.VARCHAR));
//orderdate ? how to declare parameter here
compile();
}
}
for sysdate-?
the ? parameter is to be set object of java.sql.Date class instead of java.util.Date class.
java.sql.Date inherits java.util.Date.
java.sql.Date(long time)
here long is number of milliseconds lapsed since jan1,1979.
GregorianCalendar gc=new GregorianCalendar(2000, 25, 2);
java.util.Date dt=gc.getTime();
long lg=dt.getTime();
java.sql.Date sqldt=new java.sql.Date(lg);
'
pass sqldt object in setDate() method of preparedstatement instance.
hope this works
alkaramansari1#gmail.com

Using joda DateTime in parameters for native query in spring-data-jpa fails because of bad binding

Here are two queries that should be exactly the same except one is marked as native and the other is not. The first one works fine, but the second one fails with incompatible data type in conversion
#Transactional(readOnly = true)
#Query(value = "select startDate from TaskMetrics where startDate between :startDate and :endDate")
List<DateTime> findStartDateByStartDateBetween(#Param("startDate") DateTime startDate,
#Param("endDate") DateTime endDate);
This generates the query:
select taskmetric0_.startDate as col_0_0_ from TaskMetrics taskmetric0_ where taskmetric0_.startDate between ? and ?
With bindings
binding parameter [1] as [TIMESTAMP] - [2015-02-02 10:57:14.279]
binding parameter [2] as [TIMESTAMP] - [2015-02-04 10:57:14.281]
-
#Transactional(readOnly = true)
#Query(nativeQuery = true, value = "select startDate from TaskMetrics where startDate between :startDate and :endDate")
List<DateTime> findStartDateBetween(#Param("startDate") DateTime startDate,
#Param("endDate") DateTime endDate);
This generates the query:
select startDate from TaskMetrics where startDate between ? and ?
With one binding, which also seems a bit odd (especially why #2?):
binding parameter [2] as [VARBINARY] - [2015-02-04T10:57:14.315-05:00]
I'm using Hibernate 4.3.8.Final as my JPA 2.1 provider and Jadira Usertype 3.1.0.CR10 for JodaTime support.
Am I doing something wrong or is this a bug somewhere?
Bug opened here - https://jira.spring.io/browse/DATAJPA-671
Workaround for the bug:
public class MyDaoClass {
// Converter provided by joda time user type library
private TimestampColumnDateTimeMapper columnDateTimeMapper = new TimestampColumnDateTimeMapper();
#Override
public void doAction(MyObject myObject) {
Query q = getEntityManager().createNamedQuery("MyNativeNamedQuery");
q.setParameter("date", columnDateTimeMapper.toNonNullValue(myObject.getDate()), TemporalType.TIMESTAMP);
q.executeUpdate(); // or select
}
The second one is a nativeQuery as i know the will not work with joda DateTime. use Java.sql.Date instead.

Categories

Resources