Search for a String in a column of List of Strings using Spring jpa query - spring-boot

I have a Spring Boot application and I am using Spring Data JPA to query a PostgreSQL database.
I have a column of List type in my database. Now I need a query to search all those rows where my input parameter is present in this list.
eg. I have a column of type List containing any of these values: ["cat","dog","cow"].
I need to find all those rows where "cat" is one among the list.
Can you help me with the format of this query? Thanks in advance.

From what I could understand, you have a DB table, let's say Sample. Now this table has multiple columns with one column whose values can be either of "cat","dog","cow". Let's assume the column name to be 'sampleName'.
So, in your code you must be having an #Entity class for Sample with #Column sampleName, and a corresponding JPA repository - SampleRepository.
Now, the code for requirement should look like as shown below:
public interface SampleRepository extends JpaRepository<Sample, Long> {
Optional<Sample> findBySampleName(String sampleName);
}
In above JPA repository, I have assumed that you have an #Id field of type Long in your entity Sample. Also, I have made use of method-name strategy. Spring boot will automatically translate this method name to a SQL query at run time like - SELECT * FROM sample WHERE sampleName = 'cat'. This value cat will be provided to your repository method as an argument from #Service layer.
Hope this helps!
In addition to this, you can also choose to use the native query approach. Please refer - https://www.baeldung.com/spring-data-jpa-query for more details.

Related

Derived delete query in Spring Data JDBC not working

I've put a derived query on a CrudRepository<Customer, Long> that should delete all entities with a given businessId (which is not the primary key but just another, non-unique column), of which there can be many.
In my SpringDataJdbcTest test, I first save 2 customers with the same businessId.
Then, I want to call the following method on the CrudRepository:
fun deleteAllByBusinessId(businessId: Long)
But it gives me:
org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 2
at org.springframework.dao.support.DataAccessUtils.nullableSingleResult(DataAccessUtils.java:100)
at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.queryForObject(NamedParameterJdbcTemplate.java:244)
It seems Spring Data Jdbc first wants to determine if there's a unique entity with that business Id, but of course, there are 2.
Could it be that support for such a derived delete query doesn't work correctly? I use Spring Data JDBC 2.3.5.
You are right, derived delete queries don't work yet. See https://github.com/spring-projects/spring-data-relational/issues/771

How to bulk delete from a JPA repository in Spring Data receiving a list filled with one of the properties from my Entity class

I have an Entity that has four properties, (vehicle, unit, date and id). Primary key is the ID.
I want to delete rows from the database based on the vehicle list provided to me via a request body.
How can I take all the lists and use them to delete data from the database at once?
You can create a "delete...By" query in your Entity repository that takes a List of Vehicle as a parameter and deletes all entities that their Vehicle is contained in that List.
Something like this should work:
void deleteAllByVehicle(List<Vehicle> vehicles);
The documentation contains more options:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
you can use JPQL to provide custom query
#Query(delete from Entity e where e.idvehicle = :id)
void deleteByVehicle(#Param("id") int idvehicle);
now you can just pass the id of the Vehicle like that:
deleteByVehicle(vehicle.getId());

Is it necessary to use Entity annotation for Select query records from Database

I have spring boot application with JPA and MySQL. The table is already created and data are present. From the spring boot application, we need to create two API - get a particular record using id and get all the records. I created a model class but confused with usage of #Entity. Because I'm not going to insert/delete a record from the database. I want to use only for select the record.
For Select query (findBy), do we need to use #Entity annotation at the top of model class?
Yes, you would need to use #Entity to mark your model class, this tells JPA that your class is used for mapping to and from a database table. If you want to make sure that you don't accidentally overwrite the data, you could implement a check via #EntityListener, as described in this answer.

Handling filtering by a particular field in JPA Spring Boot

I want to implement a filtering feature based on the properties of an entity that I have stored in my db.
I'm using a JPA query to do so. The problem that I'm facing is concerned with entity manager which requires the class of the object that is required to return.
public List<CountryEntity> getSortedCountries(String field, String type) {
return entityManager.createQuery(GET_ALL_SORTED.concat(field).concat(" " + type), CountryEntity.class).getResultList();
}
When I select only one field, let's say the name of the country, the query returns a String and not an object of type CountryEntity.
What is the best approach to handle this problem? Should I create classes for every single case or is there another way that I'm missing?

Spring Data CrudRepository custom ID generator

I am using spring boot(1.4),spring data and jpa. And using #Repository(CrudRepository)
One of my Table/Entity, the ID column, I want to generate customised string.
Start with some specific string plus creation data and time, and end with next value from db.
so here I can't use #TableGenerator, I need some native query like "select nextvalue "
Is there better way can achieve this.
Add a "normal" ID column using #Id and #GeneratedValue and then manually fill your special column after the entity has been stored the first time.

Resources