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