【问题标题】:Why is my Query response returning Null Values?为什么我的查询响应返回空值?
【发布时间】:2021-11-30 22:35:01
【问题描述】:

我有一个客户类,我想做的是从客户实体中单独调用客户名字和姓氏字段,以填充投资表格中的客户名称下拉字段。我使用接口添加了一个投影,但响应值为 null。

这是客户

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;

这是投影

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

这是 repository

@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();
}



这是服务

@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;
        }
    
  }


这是控制器

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

【问题讨论】:

    标签: java mysql reactjs spring-boot jpa


    【解决方案1】:

    你想做的事情不会这样。

    首先你有一个JpaRepository &lt;Customer, Long&gt;,实体的类型是Customer,id是Long。所以这个JpaRepo 的查询将处理only Customer 对象。

    如果您只需要 firstNamelastName 的对象,则创建一个 class (DTO) 只有这些并将您的查询更改为:

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

    P.S.:如上所示,您需要为 DTO 创建一个构造函数。

    【讨论】:

    • 这就像上面指定的那样工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2011-11-24
    • 2016-03-21
    • 1970-01-01
    • 2020-01-22
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多