Reputation: 1965
Is it possible (if so, how) would one add custom methods in the CrudRepository interface?
I have the following DAO with a entity class called, Foobar. For the sake of this question - the entity class can have any number of fields/columns.
package com.bar
import org.springframework.data.repository.CrudRepository;
import com.bar.Foobar
public interface FoobarCrudRepo extends CrudRepository<Foobar, Long> {
public Foobar findByObject(Foobar JObj);
}
This code works fine if you remove that custom method but throws an error if I add it (like above). My understanding from this post (Update or SaveorUpdate in CRUDRespository, Is there any options available) was that I just needed to add an additional method to the interface (as shown in the example) and the JPARepo will take care of the rest. However, I'm getting the error below. My thinking - it doesn't know much about this custom class.
Here's my error:
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Foobar': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property object found for type Foobar!
Why would I want a findbyObject() you might ask? So that I don't insert duplicate rows of data into the DB by checking the DB to see if the object has already been added and performing a check.
Any suggestions would help, thanks.
Upvotes: 0
Views: 843
Reputation: 708
FindByObject
doesn't look for an object, it literally looks for a field in your Foobar
class named Object
. Like others have mentioned, you can check other fields of the object to see if it already exists.
For example, if your Foobar
class has String name
and String email
fields, you could create a method like public Foobar findByNameAndEmail(String name, String email) {}
, and this would return a Foobar object if there was a record in the database that met these criteria.
All query methods do is replicate SQL, so ask yourself, could you "find by object (record)" in SQL? No, because that makes no sense. Your query would return a record (object) WHERE certain conditions are met.
Upvotes: 1
Reputation: 36133
Your code does not work because it takes the Names behind findBy and tries to create the where condition with that.
So findByObject creates:
where object = ?
to find the object by id you can call
findOne(?)
Upvotes: 0