Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

using Spring DATA to implement DAO

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?

Example:

1) interface

/* this is the interface */  
public interface AccountRepository extends JpaRepository
{
    List<Account> getAllAccounts();
}

2) implementation ?

public class AccountRepositoryImpl implements AccountRepository
{
    public List<Account> getAllAccounts() {
        // now what?
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...