Different between Query keywords Containing, IsContaining, Contains in Spring Data JPA
Asked Answered
F

2

12

What is different between Query keywords Containing, IsContaining, Contains in Spring Data ?

List<Movie> findByTitleContaining(String title);
List<Movie> findByTitleContains(String title);
List<Movie> findByTitleIsContaining(String title);
Friedafriedberg answered 13/11, 2020 at 3:14 Comment(1)
You can also, add the hibernate...show.sql=true to see theselect sql statement generated for both.Casing
B
15

There is no difference, they mean the same thing.

Biddy answered 13/11, 2020 at 3:26 Comment(0)
A
1

Containing: Used for substring searches within string fields. It translates to the SQL LIKE operator with wildcards (%substring%).

Contains: Used for checking membership within collection fields (e.g., List, Set). It is useful for querying if a collection contains a specific element.

On the other hand both Containing and isContaining serve the same purpose and are interchangeable in terms of functionality. The choice between them depends on which naming convention fits better with your method naming style and improves code readability.


----- Containing Example -----

Entity

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // getters and setters
}

Repository:

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByNameContaining(String namePart);
    //or
    List<User> findByNameIsContaining(String namePart);

}

----- Contains Example -----

Entity

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @ManyToMany
    private Set<Author> authors;
    // getters and setters
}

Repository:

public interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByAuthorsContains(Author author);
}
Amadeus answered 18/6 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.