JPA @ManyToOne 只有 JSON swagger body 中的 ID?
JPA @ManyToOne Only having the ID in the JSON swagger body?
我创建了一个 JPA object,它与另外 2 个 object 有 @ManyToOne
关系。但是我在让它工作时遇到了问题。特别是关于 JSON body。如果它们看起来不重要,我已经删除了一些注释
public class Booking implements Serializable {
@Id
@ApiModelProperty(readOnly = true)
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@NotNull
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.DETACH)
@JoinColumn(name = "customer_id")
private Customer customer;
@NotNull
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.DETACH)
@JoinColumn(name = "taxi_id")
private Taxi taxi;
@NotNull
@Future(message = "Bookings can not be in the past. Please choose one from the future")
@Column(name = "booking_date")
@Temporal(TemporalType.DATE)
private Date bookingDate;
}
public class Customer implements Serializable {
@Id
@ApiModelProperty(readOnly = true)
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@OneToMany(mappedBy = "taxi", cascade = CascadeType.ALL)
@ApiModelProperty(hidden = true)
private List<Booking> bookings;
}
public class Taxi implements Serializable {
@Id
@ApiModelProperty(readOnly = true)
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
private String registration;
private String numberOfSeats;
@OneToMany(mappedBy = "taxi", cascade = CascadeType.ALL)
@ApiModelProperty(hidden = true)
private List<Booking> bookings;
}
休息服务
public Response createBooking(
@ApiParam(value = "Customer ID, Taxi ID and a booking date required to create a booking", required = true)
org.jboss.quickstarts.wfk.booking.Booking booking)
{
if (booking == null) {
throw new RestServiceException("Bad Request", Response.Status.BAD_REQUEST);
}
Response.ResponseBuilder builder;
try {
// Go add the new Booking.
service.create(booking);
builder = Response.status(Response.Status.CREATED).entity(booking);
} catch (ConstraintViolationException ce) {
//Handle bean validation issues
Map<String, String> responseObj = new HashMap<>();
for (ConstraintViolation<?> violation : ce.getConstraintViolations()) {
responseObj.put(violation.getPropertyPath().toString(), violation.getMessage());
}
throw new RestServiceException("Bad Request", responseObj, Response.Status.BAD_REQUEST, ce);
} catch (Exception e) {
// Handle generic exceptions
throw new RestServiceException(e);
}
log.info("createBooking completed. Booking = " + booking.toString());
return builder.build();
}
服务 class 其中 crud 是存储库
@Inject
private BookingRepository crud;
Booking create(Booking booking) throws ConstraintViolationException, ValidationException, Exception {
log.info("BookingService Testing: " + booking.toString());
log.info("BookingService.create() - Creating " + booking.getCustomer().getId() + " " + booking.getTaxi().getId());
// Check to make sure the data fits with the parameters in the Booking model and passes validation.
//validator.validateBooking(booking);
// Write the booking to the database.
return crud.create(booking);
}
存储库class
@Inject
private EntityManager em;
Booking create(Booking booking) throws ConstraintViolationException, ValidationException, Exception {
log.info("BookingRepository.create() - Creating " + booking.getCustomer().getId() + " " + booking.getTaxi().getId());
// Write the booking to the database.
em.persist(booking);
return booking;
}
但是当我查看我的 swagger 文档时,它显示了这一点。但我不想创建新的 object。我想访问 ID 为
的 objects
{
"customer": {
"firstName": "string",
"lastName": "string",
"email": "string",
"phoneNumber": "string"
},
"taxi": {
"registration": "string",
"numberOfSeats": 0
},
"bookingDate": "2021-11-11T22:20:34.952Z"
}
所以我想将其发送为 body
{
"customer_id": 0,
"taxi_id": 0,
"bookingDate": "2021-11-11T22:20:34.952Z"
}
有人body对此有什么解决办法吗?如果您需要更多代码,请告诉我。
您需要更改 RestService
以接受以下实例 class 而不是 Booking
:
public class BookingCreationRequest {
@JsonProperty("customer_id")
private Long customerId;
@JsonProperty("taxi_id")
private Long taxiId;
private Date bookingDate;
}
所以你的 RestService
中的内容类似于以下内容:
public Response createBooking(BookingCreationRequest bookingCreationRequest) {
(...)
service.create(bookingCreationRequest);
(...)
}
现在在您的服务 class 中,您需要获取与请求关联的 Customer
和 Taxi
实体,构建 Booking
对象并将其持久化在数据库中:
@Inject
private BookingRepository crud;
@Inject
private TaxiService taxiService;
@Inject
private CustomerService customerService;
Booking create(BookingCreationRequest bookingCreationRequest) throws ConstraintViolationException, ValidationException, Exception {
(...)
Taxi taxi = taxiService.getTaxiById(bookingCreationRequest.getTaxiId());
Customer customer = customerService.getCustomerById(bookingCreationRequest.getCustomerId());
Booking booking = new Booking();
booking.setTaxi(taxi);
booking.setCustomer(customer);
booking.setBookingDate(bookingCreationRequest.getBookingDate());
return crud.create(booking);
}
我创建了一个 JPA object,它与另外 2 个 object 有 @ManyToOne
关系。但是我在让它工作时遇到了问题。特别是关于 JSON body。如果它们看起来不重要,我已经删除了一些注释
public class Booking implements Serializable {
@Id
@ApiModelProperty(readOnly = true)
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@NotNull
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.DETACH)
@JoinColumn(name = "customer_id")
private Customer customer;
@NotNull
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.DETACH)
@JoinColumn(name = "taxi_id")
private Taxi taxi;
@NotNull
@Future(message = "Bookings can not be in the past. Please choose one from the future")
@Column(name = "booking_date")
@Temporal(TemporalType.DATE)
private Date bookingDate;
}
public class Customer implements Serializable {
@Id
@ApiModelProperty(readOnly = true)
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@OneToMany(mappedBy = "taxi", cascade = CascadeType.ALL)
@ApiModelProperty(hidden = true)
private List<Booking> bookings;
}
public class Taxi implements Serializable {
@Id
@ApiModelProperty(readOnly = true)
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
private String registration;
private String numberOfSeats;
@OneToMany(mappedBy = "taxi", cascade = CascadeType.ALL)
@ApiModelProperty(hidden = true)
private List<Booking> bookings;
}
休息服务
public Response createBooking(
@ApiParam(value = "Customer ID, Taxi ID and a booking date required to create a booking", required = true)
org.jboss.quickstarts.wfk.booking.Booking booking)
{
if (booking == null) {
throw new RestServiceException("Bad Request", Response.Status.BAD_REQUEST);
}
Response.ResponseBuilder builder;
try {
// Go add the new Booking.
service.create(booking);
builder = Response.status(Response.Status.CREATED).entity(booking);
} catch (ConstraintViolationException ce) {
//Handle bean validation issues
Map<String, String> responseObj = new HashMap<>();
for (ConstraintViolation<?> violation : ce.getConstraintViolations()) {
responseObj.put(violation.getPropertyPath().toString(), violation.getMessage());
}
throw new RestServiceException("Bad Request", responseObj, Response.Status.BAD_REQUEST, ce);
} catch (Exception e) {
// Handle generic exceptions
throw new RestServiceException(e);
}
log.info("createBooking completed. Booking = " + booking.toString());
return builder.build();
}
服务 class 其中 crud 是存储库
@Inject
private BookingRepository crud;
Booking create(Booking booking) throws ConstraintViolationException, ValidationException, Exception {
log.info("BookingService Testing: " + booking.toString());
log.info("BookingService.create() - Creating " + booking.getCustomer().getId() + " " + booking.getTaxi().getId());
// Check to make sure the data fits with the parameters in the Booking model and passes validation.
//validator.validateBooking(booking);
// Write the booking to the database.
return crud.create(booking);
}
存储库class
@Inject
private EntityManager em;
Booking create(Booking booking) throws ConstraintViolationException, ValidationException, Exception {
log.info("BookingRepository.create() - Creating " + booking.getCustomer().getId() + " " + booking.getTaxi().getId());
// Write the booking to the database.
em.persist(booking);
return booking;
}
但是当我查看我的 swagger 文档时,它显示了这一点。但我不想创建新的 object。我想访问 ID 为
的 objects{
"customer": {
"firstName": "string",
"lastName": "string",
"email": "string",
"phoneNumber": "string"
},
"taxi": {
"registration": "string",
"numberOfSeats": 0
},
"bookingDate": "2021-11-11T22:20:34.952Z"
}
所以我想将其发送为 body
{
"customer_id": 0,
"taxi_id": 0,
"bookingDate": "2021-11-11T22:20:34.952Z"
}
有人body对此有什么解决办法吗?如果您需要更多代码,请告诉我。
您需要更改 RestService
以接受以下实例 class 而不是 Booking
:
public class BookingCreationRequest {
@JsonProperty("customer_id")
private Long customerId;
@JsonProperty("taxi_id")
private Long taxiId;
private Date bookingDate;
}
所以你的 RestService
中的内容类似于以下内容:
public Response createBooking(BookingCreationRequest bookingCreationRequest) {
(...)
service.create(bookingCreationRequest);
(...)
}
现在在您的服务 class 中,您需要获取与请求关联的 Customer
和 Taxi
实体,构建 Booking
对象并将其持久化在数据库中:
@Inject
private BookingRepository crud;
@Inject
private TaxiService taxiService;
@Inject
private CustomerService customerService;
Booking create(BookingCreationRequest bookingCreationRequest) throws ConstraintViolationException, ValidationException, Exception {
(...)
Taxi taxi = taxiService.getTaxiById(bookingCreationRequest.getTaxiId());
Customer customer = customerService.getCustomerById(bookingCreationRequest.getCustomerId());
Booking booking = new Booking();
booking.setTaxi(taxi);
booking.setCustomer(customer);
booking.setBookingDate(bookingCreationRequest.getBookingDate());
return crud.create(booking);
}