java为什么我的查询响应返回空值?
我有一个customer类,我想做的是从customer实体中单独调用customer firstname和Lastname字段,以填充投资表单中的customer Name下拉字段。我使用接口添加了一个投影,但响应值为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
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();
}
# 1 楼答案
你想做的事情不会这样做
首先,您有一个
JpaRepository <Customer, Long>
,实体的类型是Customer
,id是Long
。因此JpaRepo
的查询将只处理对象若您只需要使用
firstName
和lastName
的对象,那个么创建一个class
(DTO),它只有这些,并将您的查询更改为:附言:如上所示,您的
DTO
需要一个构造函数