hibernate 我如何检索作为字段关联到实体类中的对象列表?

oknwwptz  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(150)

当我通过他们的任何字段找到一个Customer时,一切都很顺利,我得到了返回全局对象的JSON。
我正在编写一段代码,通过lastName查找Customer。Customer实体有一个对象,其中声明了字段lastName。因此,我希望我的Endpoint像第一种情况一样返回Customer全局对象。
我已经进入我的 Postman 状态200好,但与和空的身体。任何解决方案?谢谢

这里是一个示例,lastName字段同时声明到prefBillAddressUid和prefShipAddressUid对象中

@Entity
@Table(name = "tcustomer")
public class Customer implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@SequenceGenerator(name = "pk_sequence",sequenceName = "sequence_tcustomer",initialValue = 1000, allocationSize = 100)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_sequence")
private Long uidpk;

@Column(name = "user_id", nullable=false)
private String userId;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "pref_bill_address_uid")
private CustomerAddress prefBillAddressUid;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "pref_ship_address_uid")
private CustomerAddress prefShipAddressUid;

...

//getters and setters 
//constructors

 }

我的存储库

@Query(value = "SELECT c FROM CustomerAddress c WHERE c.lastName = :lastName")
  CustomerAddress findByLastName(   @Param("lastName") String lastName);

服务实施

@Override
    public CustomerAddressDto findByLastName(String lastName) {
    CustomerAddress result = customerRepository.findByLastName(lastName);
    return customerAddressMapper.customerAddressToCustomerAddressDto(result);
}

这里是我的资源

@GetMapping(SEARCH_CUSTOMER_LAST_NAME_ENDPOINT)
@ResponseStatus(value = HttpStatus.OK)
@ApiResponses(value = {
        @ApiResponse(code = 200,  message = "OK", response = CustomerAddressDto.class),
        @ApiResponse(code = 500, message = "Unexpected error", response = CustomerAddressDto.class)
})
@Timed
public  ResponseEntity getCustomerByLastName ( @PathVariable String lastName) throws URISyntaxException {
    if (log.isDebugEnabled()){
        log.debug("[CustomerResource] GET {} : Retrieving Customer ({})", SEARCH_CUSTOMER_LAST_NAME_ENDPOINT, lastName);
    }

    CustomerAddressDto customerAddressDto = customerService.findByLastName(lastName);

    return Optional.ofNullable(customerAddressDto)
            .map(result->{
                if (log.isDebugEnabled()){
                    log.debug("[CustomerResource] Customer ({}) retrieved", result.getLastName());
                }
                return new ResponseEntity<>(HttpStatus.OK);
            })
            .orElse(new ResponseEntity(new ResponseError(HttpStatus.NOT_FOUND.getReasonPhrase(),
                    "The Customer with lastName " + lastName + " does not exists"), null,HttpStatus.NOT_FOUND)
            );
}

customerAddress类

@Entity
@Table(name="taddress")
public class CustomerAddress implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@SequenceGenerator(name = "pk_sequence",sequenceName = "sequence_taddress",initialValue = 1000, allocationSize = 100)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "pk_sequence")
private Long uidpk;

@Column(name = "last_name")
private String lastName;

@Column(name = "first_name")
private String firstName;

@Column(name = "phone_number")
private String phoneNumber;

@Column(name= "fax_number")
private String faxNumber;

@Column(name = "street_1")
private String street1;

@Column(name= "street_2")
private String street2;

@Column(name= "city")
private String city;

@Column(name= "sub_country")
private String subCountry;

@Column(name= "zip_postal_code")
private String zipPostalCode;

@Column(name= "country")
private String country;

@Column(name = "commercial")
private Boolean commercial;

@Column(name = "guid", nullable=false)
private String guid;

@Column(name = "customer_uid")
private Long customerUid;

@Column(name= "type")
private String type;

@Column(name = "organization")
private String organization;

...
//getters ans setters
}
bvn4nwqk

bvn4nwqk1#

首先,您不能从CustomerRepository返回CustomerAddress。
一些替代方案包括
1.要从CustomerRepository中根据姓氏检索CustomerAddress,可以执行以下操作
Customer findByPrefBillAddressUid_LastName(String lastName);
spring-data将公式化查询,你不需要@Query。但请注意,返回类型是Customer而不是CustomerAddress。因此,你将获得一个具有正确customerAddress的customer对象。
1.如果希望返回CustomerAddress,那么需要创建CustomerAddressRepository并编写如下方法
CustomerAddress findByLastName(String lastName);
1.使用投影创建如下界面

interface CustomerShort {
    CustomerAddress getPrefBillAddressUid();
}

然后你的CustomerRepository需要有这样一个方法

interface CustomerRepository extends CRUDRepository<Customer, UUID> {

  Collection<CustomerShort> findByPrefBillAddressUid_LastName(String lastName);
}

相关问题