我有一個客戶類,我想要做的是從客戶物體中單獨呼叫客戶名字和姓氏欄位以填充投資表單中的客戶名稱下拉欄位。我使用介面添加了一個投影,但回應值為 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();
}
uj5u.com熱心網友回復:
你想做的事情不會這樣。
首先你有一個JpaRepository <Customer, Long>,物體的型別是Customer和 id Long。所以 this 的查詢JpaRepo將只 處理Customer物件。
如果您只需要物件firstName,lastName然后創建一個class只有這些物件的
(DTO)并將您的查詢更改為:
....
@Query(value="SELECT new path.to.your.package.CustomerDTO(c.firstName, c.lastName) "
"FROM Customer c")
List<CustomerDTO> findByFirstNameAndLastName();
PS:DTO如上所示,您需要一個建構式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318570.html
