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

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);

Related

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

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"));

How to query a Spring Repository with native SQL

I have a simple React/Spring-Boot app that creates and stores licenses. I'm trying to figure out how to incorporate a search function into the app.
The basic concept is the user enters a string and presses a "search" button which will trigger a query to the API in Spring Boot:
license/search/{searchString}
The query will search for the same string in a number of different fields. For example
select * from licenses where company like "'%" + searchString + "%'" or product like "'%" + searchString + "%'" or etc...
How can this be coded using a repository in Spring boot? I already have the controller repository created, but I need to know how to create the query.
Edit: this is the current repository:
public interface LicenseRepository extends JpaRepository<License, Long>
{
License findByFullName(String fullName);
List<License> findAllByUserId(String id);
}
Your current attempted query may be too complex for a query method. Instead, consider using the #Query annotation:
#Query("SELECT l FROM License l WHERE l.company LIKE %:company% OR p.product LIKE %:product%")
List<Movie> searchByCompanyLikeOrProductLike(#Param("company") String company, #Param("product") String product);

can we pass parameters in view of a table in SQL?

Is there any way to pass parameters to a view in postgresql? or any alternative of passing parameter from spring jpa native query
You have 2 ways to pass params to a query in JPA
Using index, here spring data will pass method parameters to the query in the same order they appear in the method declaration:
#Query(value = "SELECT * FROM FOO WHERE id = ?1", nativeQuery = true)
findById(Integer id);
By Names using #Param annotation in the method declaration to match parameters defined
#Query(value = "SELECT * FROM FOO WHERE id = :id", nativeQuery = true)
findById(#Param("id")Integer id);

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 ;)

Spring-Data JPA: How to make a jpa criteria query

Given this two entities:
post post_category
- id - post_id
- title - name
- text
I'd like to make this query using jpa criteria query:
select * from post
where post.id in (
select post_id from post_category
where name = '<category1>' and name = '<category2>' ... and name = '<categoryN>')
Looking at your query sketch I think it will not return any results. I have changed it to mean name in ('<category1>','<category2>', ...) instead. Which may not match your case.
This assumes that you have your mapping set up properly on your classes for JPA to work. For example
class PostCategory {
private String name;
private Post post;
...
#ManyToOne
public Post getPost() {
return post;
}
...
In which case your DAO code would resemble this (given a List nameValues object)
// Set up the subquery
DetachedCriteria dc = DetachedCriteria.forClass(PostCategory.class)
.setProjection(Projections.property("post.id"))
.add(Restrictions.in("name", nameValues));
Criteria crit = session.createCriteria(Post.class)
.add(Subqueries.eqProperty("id", dc));
But if you want a list of Post objects which have ALL of the categories then you will need to make a separate DetachedCriteria instance for each category and add each as an AND'ed Subquery.

Resources