How to add custom method to Spring Data JPA

后端 未结 12 2015
盖世英雄少女心
盖世英雄少女心 2020-11-22 12:58

I am looking into Spring Data JPA. Consider the below example where I will get all the crud and finder functionality working by default and if I want to customize a finder t

12条回答
  •  遥遥无期
    2020-11-22 13:20

    This is limited in usage, but for simple custom methods you can use default interface methods like:

    import demo.database.Customer;
    import org.springframework.data.repository.CrudRepository;
    
    public interface CustomerService extends CrudRepository {
    
    
        default void addSomeCustomers() {
            Customer[] customers = {
                new Customer("Józef", "Nowak", "nowakJ@o2.pl", 679856885, "Rzeszów", "Podkarpackie", "35-061", "Zamknięta 12"),
                new Customer("Adrian", "Mularczyk", "adii333@wp.pl", 867569344, "Krosno", "Podkarpackie", "32-442", "Hynka 3/16"),
                new Customer("Kazimierz", "Dejna", "sobieski22@weebly.com", 996435876, "Jarosław", "Podkarpackie", "25-122", "Korotyńskiego 11"),
                new Customer("Celina", "Dykiel", "celina.dykiel39@yahoo.org", 947845734, "Żywiec", "Śląskie", "54-333", "Polna 29")
            };
    
            for (Customer customer : customers) {
                save(customer);
            }
        }
    }
    

    EDIT:

    In this spring tutorial it is written:

    Spring Data JPA also allows you to define other query methods by simply declaring their method signature.

    So it is even possible to just declare method like:

    Customer findByHobby(Hobby personHobby);
    

    and if object Hobby is a property of Customer then Spring will automatically define method for you.

提交回复
热议问题