Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Spring Data's MongoRepository so limited?

So I notice that Spring Data's MongoTemplate has a lot of different types of "save object" operations, like save, upsert, insert, and updateFirst.

Spring Data's MongoRepository interface, on the other hand, has one persistence method: "save". Now, obviously, if I want create / update / upsert functionalities, I can implement them pretty easily. Just do a get before you call "save" and check if the entity exists or not. But it seems strange that MongoTemplate has such a diversity of options (I can't even figure out what the difference between a save and an upsert is), but Spring Data's repos are so limited.

Do you think it's wasteful / lazy to use Spring Data MongoRepositories without customizing its methods if you're going to be using create / update semantics, or is the difference between a get + null check + repository.save vs. a mongoTemplate.insert too irrelevant to care about?

like image 879
CorayThan Avatar asked Jul 23 '13 05:07

CorayThan


1 Answers

You can customize your own repository using XXXRepositoryCustom and writing an implementation for it.

Here is an example:

public interface AccountRepository extends MongoRepository<Account, String>, AccountRepositoryCustom{

    @Query("{ 'email' : ?0 }")
    Account findByEmail(String email);

}

Notice the above interface extends your own AccountRepositoryCustom interface.

Then define your own AccountRepositoryCustom:

public interface AccountRepositoryCustom {

    public boolean updateAccountToken(String id, String token);

}

Next, write a implementation for it:

public class AccountRepositoryCustomImpl implements AccountRepositoryCustom {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public boolean updateAccountToken(String id, String token) {    
            // your code 
    }
}
like image 143
Han Wang Avatar answered Sep 23 '22 02:09

Han Wang