Spring Data JPA - how to filter returned data based on a fields values? - spring-boot

I am trying to figure out how do I filter what data is being returned to me in Spring JPA.
I know that with Spring JDBC, I get full controll and I can basically write a query like:
SELECT * FROM CAR
WHERE ACCIDENT_DATE IS NULL
OR BUY_DATE >= CURRENT_DATE
ORDER BY CAR_NUMBER
But, with Spring JPA, we dont write queries, instead we write entities like
#Entity
#Table(name = "CAR", schema = "MY_SCHEMA")
public class Car {
#Id
public Long carNumber;
...
}
What is the way to filter which Cars are returned based on weather the
ACCIDENT_DATE is NULL and
BUY_DATE is greater than CURRENT_DATE
, ordered by CAR_NUMBER in Spring JPA?

With the help of #DirkDayne, figured out how to do this. Thank you Dirk
#Query("select c from CarEntity c where c.accidentDate is null or c.buyDate >= CURRENT_DATE")
List<CarEntity> getAllAvailableCars(Sort sort);
, then call it in service as:
List<CarEntity> cars= (List<CarEntity>) carRepository.getAllAvailableCars(Sort.by("carNumber"));

Related

How can I write a custom query with spring in mongo?

I'm trying to make a query and fetch data over mongodb with Spring. But I don't know mongo and spring very well. I have these fields in my table. How can I write a custom query with this query in SQL? I mean give the qp value of the record whose id is this. How can I write this please help..
SELECT qp
FROM tableName
WHERE id = request.getId();
my custom query method is it true?
public Object findQueryParams(ProcessInfo processInfo ){
Query query = Query.query(Criteria.where("id").is(processInfo .getId()).is(processInfo .getQueryParams()));
return query;
}

How to use Customize your Queries in JPA with Query Methods (spring boot)

I want to retrieve a specific value from the database based on a criteria without using the query method in Spring JPA.
they query desired is
SELECT TOP 1 * FROM Co2 WHERE Co2.room = ?1 order by co2.id desc
which can be used in a normal native query annotation like so:
public interface Co2Respository extends CrudRepository<Co2, Integer> {
#Query("SELECT TOP 1 * FROM Co2 WHERE Co2.room = ?1 order by co2.id desc",
nativeQuery = true)
Co2 findLastInsertedValueForRoom(int id);
}
the question is how to achieve the same using the custom query method in Spring JPA
I will answer my own question,
the equivalent custom method for the query mentioned above is:
Co2 findTopByRoomOrderByIdDesc(Room room);

How to Return all instances of the type with the given ID in JPA SpringBoot?

I'm trying to return (or fetch) all the records from the database based on an ID provided by me. I'm using JPA and i'm aware of findAll() method but it returns all the records without any criteria, I created a custom query and it is only returning a unique value from the table but i want to return all records based on a criteria.
For example, findAllByUserID(String UserID) method should return all the records based on that UserID not just one.
I'd appreciate any help or suggestion.
Thanks
Have a look at the doc. There you will find the keywords you can use to declare methods in repository interfaces that will generate the according queries:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
In your case: If userID is an attribute of your entity you can add a method
List<YourEntity> findByfindAllByUserID(String userId)
to your repository interface.
First, make sure that you're not using any aggregate function in your select query such as DISTINCT()
Then make sure that the the method which is implementing that query is returning a List of you're desired result.
here's how it should look :
#Query("select t from table t where t.code = ?1")
List<Result> findAllByUserID(String UserID);

Run two #NamedNativeQuery query on same entity Class

I want to define two #NamedNativequery on entity class . When tying to define eclipse gives a error.
Duplicate annotation of non-repeatable type #NamedNativeQuery. Only
annotation types marked #Repeatable can be used multiple times at one
target.
From that error , I know we cannot define two define two #NamedNativeQuery of the entity class like
#Entity
#Table(name = "abc")
#NamedNativeQuery(name = "ABC.getSomeMethod1" query = "some_query",resultSetMapping ="abcDTO")//1st name query
// #NamedNativeQuery(name = "some_name" query = "some_query",resultSetMapping ="some_dto")//try to define second query , but gives error
public class ABC {
}
I am using spring repository at dao layer to called the method which bind with this query
public interface SomeInterface extends JpaRepository<ABC, Long> {
#Query(nativeQuery =true)
List<ABCDTO> getSomeMethod1(#Param("someParam1") long someParam1, #Param("someParam2") String someParam2);
}
The senario is that I want to run the 1st native sql (which run fine) query and then run the 2nd native sql query(want to run this also from same). How to solve this or What is the possible solution.
If this way I cannot run the two native sql query then is there any other to achive this.
You can define multiple named queries like this
#NamedNativeQueries({
#NamedNativeQuery(name = "ABC.getSomeMethod1"
query = "some_query",resultSetMapping ="abcDTO"
),
#NamedNativeQuery(name = "some_name"
query = "some_query",resultSetMapping ="some_dto"
)
})
Then in the business layer under the transaction you can call these two queries one after another,
If its a simple join between two entities and select and display better go with join's. Always remember to have those columns index in the Table ;)

How to get count of updated records in spring data jpa?

I am using spring data jpa with hibernate as jpa persistence provider.
I am using native queries in my application. There are some update queries and I would like to get the actual number of records updated when the update query gets executed. Is there a way in spring data jpa to do this?
I am currently following the below approach;
#Modifying
#Query(value="update table x set x_provision = ?1 where x_id = ?2", nativeQuery=true)
int updateProvision(Integer provision, Integer id);
#Transactional is added on service layer.
The problem here is that when the table gets updated I get the count as 1. But there are some cases where no rows are updated. In this case also I get the count as 1. But I would like to receive the actual number of records updated which sometimes is 0.
Can someone let me know if I am doing something wrong here?
If you take a look at ModifyingExecutor, which is used to execute this query
#Override
protected Object doExecute(AbstractJpaQuery query, Object[] values) {
int result = query.createQuery(values).executeUpdate();
if (em != null) {
em.clear();
}
return result;
}
Then you see, it only delegates to native JPA infrastructure, to return number of updated elements.
So, this might have to do with used database or ORM framework configuration, other than that, the query you wrote should return correct result.

Resources