implosivesilence
implosivesilence

Reputation: 546

How to return Map based on value of another attribute in Spring Data JPA?

Our model class is like:

@Data
@Entity
public class Address {

    private Long idDL;

    private String streetName;

    private Long pincode;
    
    private String State;
    
    private String Country;
    
    private Long addressCategory;
    
    private String status;
}

And repository class is like:

   @Repository
    public interface AddressRepository extends JpaRepository<Address, Long> {
    }

we want to return Map<Long,String> containing idDLas key and pincodeas value when status='Y'in our service layer. We don't want to write any explicit query using HQL or NativeQuery etc and want to use something like findByStatus.Is there any way to achieve this in spring data jpa?

Upvotes: 1

Views: 361

Answers (1)

nemojmenervirat
nemojmenervirat

Reputation: 179

I don't think there is a instant way of doing this. If you don't want to write any query than maybe default method in interface will be good enough:

@Repository
public interface AddressRepository extends JpaRepository<Address, Long> {

    public List<Address> findByStatus(String status);

    default public Map<Long, Long> getMap() {
        return findByStatus("Y").stream().collect(Collectors.toMap(Address::getIdDL, Address::getPincode));
    }
}

Upvotes: 2

Related Questions