Home > Mobile >  Why is my Query response returning Null Values?
Why is my Query response returning Null Values?

Time:10-12

I have a customer class , What I want to do is call the customer firstname and Lastname fields alone from the Customer entity to populate the Customer Name dropdown field in Investment Form. I added a projection using an interface but the response values are null .

Here is the customer class

public class Customer implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 8348682056500740593L;
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    
    private String firstName ;
    private String lastName;

This is the projection class

public interface CustomerInter {
    
    String getFirstName();
    String getLastName();
    
}

This is the repository class

@Repository
public interface CustomerAccountRepo extends JpaRepository <Customer, Long  > 

{

     Optional<Customer> findById(Long id);
     
    // Optional<Customer> findByFirstNameAndLastName(String firstName , String lastName);

     
     @Query(value="select c.firstName, c.lastName from Customer c")
     List<CustomerInter> findByFirstNameAndLastName();
}



This is the Service class

@Service
public class CustomerAccountService {
    
    @Autowired  
    private CustomerAccountRepo custRepo;



    public List<CustomerInter> getFirstNameAndLastNameOnly() throws Exception {
    //    LOGGER.info("Inside getAllCustomerFirst&LastName");
        List<CustomerInter> customerName = custRepo.findByFirstNameAndLastName();
        return customerName;
        }
    
  }


This is the controller class

@CrossOrigin(origins = {"http://localhost:3000"})
@RestController
public class CustomerController {
    
        @Autowired
        CustomerAccountService customerRepo;
    
        @GetMapping(value="/customerFirstAndLastName")
         public List<CustomerInter> getFirstNameAndLastNameOnly() throws Exception
         {
             
            return customerRepo.getFirstNameAndLastNameOnly();
             
         }

CodePudding user response:

What you want to do will not work this way.

First of all you have a JpaRepository <Customer, Long>, the type of the entity is Customer and the id Long. So the queries of this JpaRepo will handle only Customer objects.

If you have a need for objects only with the firstName and lastName then create a class (DTO) which has only those and change your query to this:

....

@Query(value="SELECT new path.to.your.package.CustomerDTO(c.firstName, c.lastName) "  
        "FROM Customer c")
     List<CustomerDTO> findByFirstNameAndLastName();

P.S.: You need a constructor for your DTO as seen above.

  • Related