Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find entities containing a string in a list in Spring Data Repositories

I do have a simple MongoRepository and its entities do have a List<String> tags attribute. Is there a way to add a findBy method to the repository? Something like

List<...> findByInTags(@Param("tag") String tag);

So all entities containing the given string tag in there list tags will be returned.

I tried to solve it with a RestController and a custom findByTag endpoint. But I would like to use HATEOAS for the result format.

like image 382
alexvetter Avatar asked Feb 27 '15 10:02

alexvetter


People also ask

What is @repository in spring?

Spring @Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.

What is the method name to fetch all data for a entity from database in repository class?

The Iterable<T> findAll() method returns all entities that are saved to the database. The T findOne(Long id) method returns the entity whose id is given as method parameter. If no entity is found, this method returns null.

Which method is used to fetch all rows in Spring data JPA repository?

I can use the findAll() method to select * from my_table to get all columns and rows.


1 Answers

From the spring-data-mongo unit tests: Person.java

@Document
public class Person extends Contact {
    private String firstname;
    private String lastname;
    ...
    private Set<Address> shippingAddresses;

And the PersonRepository

    /**
* Returns the {@link Person} with the given {@link Address} as shipping address.
*
* @param address
* @return
*/
Person findByShippingAddresses(Address address);

IIRC, this kind of syntax also works with Collections. So you should be able to use

List<...> findByTag(String tag);

like image 82
Martin Baumgartner Avatar answered Sep 18 '22 18:09

Martin Baumgartner