using Spring DATA to implement DAO

前端 未结 1 1420
有刺的猬
有刺的猬 2020-12-09 07:03

My requirement is this: I have to create a AccountRepository interface and i have to implement all methods in my AccountRepositoryImpl itself, so how can I do this?

相关标签:
1条回答
  • 2020-12-09 07:58

    The point of Spring Data is you don't implement the Repository. Not usually, anyway. Instead the typical usage is that you provide an interface and Spring injects some implementation that you never see.

    The very basic stuff (findOne, findAll, save, delete, etc.) is taken care of automatically by extending the org.springframework.data.repository.CrudRepository. That interface supplies the method names for you.

    Then there are cases where you can write the method signature so that Spring Data knows what to fetch (similar in concept to GORM if you know Grails), this is called "query creation by method names". You can create a method in the interface like this (copying an example from the spring data jpa documentation):

    List<Person> findByLastnameAndFirstnameAllIgnoreCase(
        String lastname, String firstname);
    

    and Spring Data will figure out the query that you need from the name.

    Finally, to handle the complex cases you can provide a Query annotation that specifies the JPQL you want to use.

    So you have a different repository interface for each entity (actually for each aggregate root). A repository for an Account entity where you want to do basic CRUD but also have a special query you want to execute might look like

    // crud methods for Account entity, where Account's PK is 
    // an artificial key of type Long
    public interface AccountRepository extends CrudRepository<Account, Long> {
        @Query("select a from Account as a " 
        + "where a.flag = true " 
        + "and a.customer = :customer")
        List<Account> findAccountsWithFlagSetByCustomer(
            @Param("customer") Customer customer);
    }
    

    and you're done, no implementation class required. (Most of the work is writing the queries and putting the right annotations on the persistent entities. And you have to wire the repositories into your spring configuration.)

    0 讨论(0)
提交回复
热议问题