How to query a Spring Repository with native SQL - spring-boot

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

Related

Find by id=1 spring data jpa

I have a table component and entity Component. I want to select id = 1 record from jpa query. Can I write 'findByIdOne' or 'findByIdEqualtoOne'? will that give me id = 1 record? Please let me know, Thanks.
No, you cannot. Refer to the Spring Data JPA documentation which documents the exact keywords that you can use.
You are free to specify the query that you want a method to execute though. Something like
#Query("select c from Component c where c.id=1")
Component findByIdOne();
I do have to put a disclaimer: by providing this solution I assume that you are really sure that ID 1 is always going to exist and will always point to exactly the same Component record in any environment that you may be running the application against. Hardcoded database IDs in your application code is not something I would ever recommend.
Direct writing the query dsl you cant, but there is a 'way' with Java 8 using default methods:
Let's say you have the query:
public interface ComponentRespository extends CrudRepository<Component, Long> {
#Query("select c from Component c where c.id=:id")
Component findById(#Param("id") Long id);
default Component findByIdOne() {
return findById(1L);
}
//eventually
default Component findByIdTwo() {
return findById(2L);
}
}
This way you can use:
private ComponentRespository componentRepository;
.....
Component componentOne = componentRepository.findByIdOne();
Component componentTwo = componentRepository.findByIdTwo();
You can use Optional<EntityName> findById(long id) or List<EntityName> findById(long id) if it's not unique.
You can use Optional<EntityName> findById(long id) or List<EntityName> findAllById if it's not unique.
We have several options:
findByIdIs(long id) or findByIdEquals(long id)

How to connect three tables using only one entity/class in Spring & Hibernate

I have only one entity which is School - a class (example). I have 7 fields in there and those fields are from 3 different tables. The first table for example is called Classroom, second is the Teachers, third is Subject. The teachers and subject table are connected by a pk: subject_id while the classroom table and teachers table are connected by classroom_id.
I tried secondary tables but it looks like it's not correct. How to connect those tables inside a single entity and write a query in the DAO IMPLementation
You should use Entity per Table.
If you need to select into non database related Model class, you can be done easily with spring-data-jpa.
After create the Model class (like School) just use the following sample to query:
class ProgrammerNameAndCity{
fields...
allArgConstructor...
}
public interface ProgrammerRepository extends JpaRepository<Programmer,Long> {
#Query(" select new com.zlrx.database.pojo.ProgrammerNameAndCity(p.name,p.address.city) " +
"from Programmer p where p.idNumber=?1")
ProgrammerNameAndCity findNameAndCityByIdNumber(String idNumber);
}
In this example the programmer has an address field (OneToOne), but you can create any kind of query, the important thing here is the constructor call of the model.
If you want to use plain sql or impl class instead of interface to query, you can use Spring's RowMapper too.
class ProgrammerNameAndCity{
fields...
allArgConstructor...
}
public interface ProgrammerRepository extends JpaRepository<Programmer,Long> {
#Query(" select new com.zlrx.database.pojo.ProgrammerNameAndCity(p.name,p.address.city) "
+ "from Programmer p where p.idNumber=?1")
ProgrammerNameAndCity findNameAndCityByIdNumber(String idNumber);
}

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

A Jpa query annotation to return results as key value pairs

I have a users table and I am trying to use annotated Queries in spring boot to get a result set. I am able to get result set as a list, but that does not have field names. How do I get the result set with field name as key and value pairs?
Current response [[1,"Jay"]] , what I want to do is {"id":1,"Name":"Jay"}
-----Here is my repository class-----
#Repository
public interface UsersauthRepository2 extends JpaRepository<Users2,Long> {
#Query("select id,name,email from Users u where LOWER(email) = LOWER(:email) and LOWER(u.password) = LOWER(:password)")
List<Users2> querybyemail(#Param("email") String email,#Param("password") String password);
}
The request doesn't return fields names.
If you need to get them :
You have them already as method argument
You need to use reflection.
Good luck

Spring data jpa Query dynamically pass where clause

My Entity is in this way
public class event
{
String title;
String description;
String city;
}
I am new to Spring data jpa ,i want implement search feature when an user enters "Hello Hyderabad Fest"
I want token size the string and split into words and find Any word matches on any properties on entity with search query hit to db.
WHERE title LIKE '%Hello%' OR title LIKE '%Hyderabad%' OR title LIKE
'%Fest%' OR description LIKE '%Hello%' OR description LIKE
'%Hyderabad%' OR description LIKE '%Fest%'city LIKE '%Hello%' OR
cityitle LIKE '%Hyderabad%' OR city LIKE '%Fest%'
How can we achieve this in spring data jpa.
Can we dynamically pass where condition in Spring data jpa named queries
Can we lucene kind query which we use in nosql dbs.
any other suggestion
Thanks in advance.
Postgresql fulltext search query solved the above issue http://rachbelaid.com/postgres-full-text-search-is-good-enough/

Resources