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

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

Related

Retrieve the deleted record spring JPA

I am working on a spring application.
We have a specific requirement where when we get a specific event, we want to look it up in the DB. If we find the record in the DB, then we delete it from DB, create another event using the details and trigger it.
Now my concern is:
I do not want to use two different calls, one to find the record and another to
delete the record.
I am looking for a way where we can delete the record using a custom
query and simultaneously fetch the deleted record.
This saves two differnet calls to DB, one for fetch and another for delete.
What I found on the internet so far:
We can use the custom query for deletion using the annotation called #Modifying. But this does not allow us to return the object as a whole. You can only return void or int from the methods that are annotated using #Modifying.
We have removeBy or deleteBy named queries provided by spring. but this also returns int only and not the complete record object that is being deleted.
I am specifically looking for something like:
#Transactional
FulfilmentAcknowledgement deleteByEntityIdAndItemIdAndFulfilmentIdAndType(#Param(value = "entityId") String entityId, #Param(value = "itemId") String itemId,
#Param(value = "fulfilmentId") Long fulfilmentId, #Param(value = "type") String type);
Is it possible to get the deleted record from DB and make the above call work?
I could not find a way to retrieve the actual object being deleted either by custom #Query or by named queries. The only method that returns the object being deleted is deleteById or removeById, but for that, we need the primary key of the record that is being deleted. It is not always possible to have that primary key with us.
So far, the best way that I found to do this was:
Fetch the record from DB using the custom query.
Delete the record from DB by calling deleteById. Although, you can now delete it using any method since we would not be requiring the object being returned by deleteById. I still chose deleteById because my DB is indexed on the primary key and it is faster to delete it using that.
We can use reactor or executor service to run the processes asynchronously and parallelly.

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

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.

is it possible to have conditional #Transient field?

Let's say if I have an Entity named person with lots of information including SSN. When other user query this person, I want to show a 'lite' version of person Entity. I could've done so by annotating SSN with #Transient, but that means the person himself would not get this field too. Is it possible to reuse the same Entity but return two different json to client? I'm using spring boot.
First of all #Transient just means that the value, the SSN in your case, won't be persisted to the database.
As for your problem annotations are static and cannot be applied dynamically.
You have 2 Options:
Define a new View class for your user.
Look at JacksonJsonViews

Treat Entity with Id NULL as NEW

To the question "Save Differences with Entity ID" I found the following answer:
"For Entities, Id property cannot be null, so you need to map this class as ValueObject. If so,
Id property is treated as regular property and it not goes to GlobalId of this object."
My question is:
Why can't an entity be treated as NEW if the Id is NULL?
I have an object graph that is fetched from the database, and between two javers commits an entity is added to a list in the graph.
Two commits and in the second commit there is a new entity (Id NULL)
Get the change => exeption because Javers can't create a GlobalId.
I can get arround this by doing EntityManager - persist (creates Id:s), but I would like to avoid doing that. The present code may do a persist later or it just lets the transaction finish.
Because the Id is NULL, the entity is NEW. Would it be possible to generate a unigue temp Id (allow Id = NULL) to be able to create the GlobalId?
In the change list, the entity would be reported as NEW. No need to compare with earlier commits.
You should compare/commit your objects when they are fully initialized so when they have Ids.
An entity without Id can't be handled by JaVers for several reasons:
it can't be compared to other entity/version (diff algorithm is based on GlobalIds)
it can't be queried from JaVersRepository (queries use GlobalIds)
If you are using Hibernate, compare/commit your new objects after Hibernate assigns them Ids from sequences.
Another options:
don't use sequence-generated values as JaVers Id but some business identifiers
if an Entity doesn't have a business identifier you can generate UUID in a constructor and use it as JaVers id (and also database PK if you like)

Can I use the auto-generated Linq-to-SQL entity classes in 'disconnected' mode?

Suppose I have an automatically-generated Employee class based on the Employees table in my database.
Now suppose that I want to pass employee data to a ShowAges method that will print out name & age for a list of employees. I'll retrieve the data for a given set of employees via a linq query, which will return me a set of Employee instances. I can then pass the Employee instances to the ShowAges method, which can access the Name & Age fields to get the data it needs.
However, because my Employees table has relationships with various other tables in my database, my Employee class also has a Department field, a Manager field, etc. that provide access to related records in those other tables. If the ShowAges method were to invoke any of those methods, this would cause lots more data to be fetched from the database, on-demand.
I want to be sure that the ShowAges method only uses the data I have already fetched for it, but I really don't want to have to go to the trouble of defining a new class which replicates the Employee class but has fewer methods. (In my real-world scenario, the class would have to be considerably more complex than the Employee class described here; it would have several 'joined' classes that do need to be populated, and others that don't).
Is there a way to 'switch off' or 'disconnect' the Employees instances so that an attempt to access any property or related object that's not already populated will raise an exception?
If not, then I assume that since this must be a common requirement, there might be an already-established pattern for doing this sort of thing?
maybe not the answer you're looking for,but how about projecting the results of your query into a more light-weight POCO, eg:
var employeePOCOs = from e in l2sEmployees
select new EmployeePOCO
{
Id = e.Id,
Name = e.FirstName + " " + e.LastName
};
where EmployeePOCO is a predefined class
would that help? I've used this when returning Entity Framework objects back through an AJAX call where the output was going to JSON, and it seemed to do the trick.
One way to do this is to 'detach' the entity from its database context. Take a look at an answer I gave to a similar question. It shows you a couple ways of detaching entities.

Resources