javaspringinterface

Question about multiple implementation of interface in Java/Spring


I have an interface:

public interface UserRepository {

    Optional<User> findById(UUID id);
    Optional<User> findByUsername(String username);

    void save(User user);
    void delete(User user);

}

This interface is implemented by two repositories - JPA and Cassandra. Jpa user model has username field in table, but cassandra doesn't have this field.

@Repository("jpaUserRepository")
@RequiredArgsConstructor
public class JpaUserRepository implements UserRepository {

    private final SpringDataJpaUserRepository springDataJpaUserRepository;
    private final JpaUserMapper jpaUserMapper;

    ....

    @Override
    public Optional<User> findByUsername(String username) {
        return springDataJpaUserRepository
                .findJpaUserEntityByUsername(username)
                .map(jpaUserMapper::toDomain);
    }

    ....
}

@Repository("cassandraUserRepository")
@RequiredArgsConstructor
public class CassandraUserRepository implements UserRepository {

    private final SpringDataCassandraUserRepository springDataCassandraUserRepository;
    private final CassandraUserMapper cassandraUserMapper;

    ....

    @Override
    public Optional<User> findByUsername(String username) {
        return Optional.empty();
    }

    ....
}

Since the user model in Cassandra does not have a username field, how can I implement the findById() method in the Cassandra repository?


Solution

  • You need to extend your interface to extend CrudRepository

    public interface UserRepository extends CrudRepository<User, UUID>
    

    Then you should get findById() from the framework. No need to provide its implementation.

    You can refer to original example and customize as per your requirement JPA example https://spring.io/guides/gs/accessing-data-jpa Cassandra example https://spring.io/guides/gs/accessing-data-cassandra