In Spring Data JPA, you can define a method in your repository interface to find entities where a field’s value is similar to a specified value using the `LIKE` keyword. The method naming convention in Spring Data JPA is crucial, and you can leverage the `findBy` keyword along with the field name and the `Containing`, `StartingWith`, `EndingWith`, or `Like` keywords to achieve this.

### Example:

Let’s say you have an entity class `Person` with a field `name`.

@Entity

public class Person {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    private String name;

    // getters and setters

}

To define a repository method that finds all `Person` entities where the `name` contains a specific string, you can do the following:

public interface PersonRepository extends JpaRepository<Person, Long> {

    List<Person> findByNameContaining(String namePart);

    List<Person> findByNameStartingWith(String nameStart);

    List<Person> findByNameEndingWith(String nameEnd);

    // Find persons where the name matches a pattern (useful for more complex patterns)

    List<Person> findByNameLike(String pattern);

}

– `Like`: This allows you to define a custom pattern using wildcards (e.g., `LIKE %name%` or `LIKE name%`).

### Examples of Usage:

// Finds persons whose name contains „John“

List<Person> personsContaining = personRepository.findByNameContaining(„John“);

// Finds persons whose name starts with „John“

List<Person> personsStartingWith = personRepository.findByNameStartingWith(„John“);

// Finds persons whose name ends with „Doe“

List<Person> personsEndingWith = personRepository.findByNameEndingWith(„Doe“);

// Finds persons whose name matches the pattern „J%n“

List<Person> personsLike = personRepository.findByNameLike(„J%n“);

Hinterlasse einen Kommentar

I’m Iman

Mein Name ist Iman Dabbaghi. Ich arbeite als Senior Software Engineer in der Schweiz. Außerdem interessiere ich mich sehr für gewaltfreie Kommunikation, Bachata-Tanz und Musik sowie fürs die Persönlichkeitsentwicklung.

Ich habe einen Masterabschluss in Informatik von der Universität Freiburg in Deutschland, bin Spring/Java Certified Professional (OCP), Certified Professional for Software Architecture (CPSA-F) und ein lebenslanger Lernender 🎓.

EN:

My name is Iman Dabbaghi. I work as a Senior Software Engineer in Switzerland. I am also very interessted in nonviolent communication, Bachata dance and music and also for personal development.

I hold a masters degree in computer science from the university of Freiburg in Germany, am a Spring / Java Certified Professional (OCP), Certified Software Architecture (CPSA-F) and Life Long Learner🎓

Let’s connect