Spring引导REST CRUD-如何发布具有一对一关系的实体



我有一个非常简单的域模型:"Alert"有一个"Type"和一个"Status"。

这是我的模式:

create table `price_alert_status` (
`id` bigint(20) not null,
`status_name` varchar(64) not null,
primary key (`id`),
unique key (`status_name`)
) engine=InnoDB default charset=utf8;
insert into `price_alert_status` values (0, 'INACTIVE');
insert into `price_alert_status` values (1, 'ACTIVE');
create table `price_alert_type` (
`id` bigint(20) not null,
`type_name` varchar(64) not null,
primary key (`id`),
unique key (`type_name`)
) engine=InnoDB default charset=utf8;
insert into `price_alert_type` values (0, 'TYPE_0');
insert into `price_alert_type` values (1, 'TYPE_1');
create table `price_alert` (
`id` bigint(20) not null auto_increment,
`user_id` bigint(20) not null,
`price` double not null,
`price_alert_status_id` bigint(20) not null,
`price_alert_type_id` bigint(20) not null,
`creation_date` datetime not null,
`cancelation_date` datetime null,
`send_periodic_email` tinyint(1) not null,
`price_reached_notifications` tinyint(4) default '0',
`approximate_price_notifications` tinyint(4) null,
`notify` tinyint(1) not null default '1',
primary key (`id`),
constraint `FK_ALERT_TO_ALERT_STATUS` foreign key (`price_alert_status_id`) references `price_alert_status` (`id`),
constraint `FK_ALERT_TO_ALERT_TYPE` foreign key (`price_alert_type_id`) references `price_alert_type` (`id`)
) engine=InnoDB default charset=utf8;

现在,我将展示各自的实体类:

Alert.java:

// imports omitted
@Entity
@Table(name = "price_alert")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"creationDate"}, 
allowGetters = true)
public class Alert implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long userId;
private double price;
@OneToOne
@JoinColumn(name = "price_alert_status_id", nullable = false)
private Status status;
@OneToOne
@JoinColumn(name = "price_alert_type_id", nullable = false)
private Type type;
@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date creationDate;
@Column(nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date cancelationDate;
private boolean sendPeriodicEmail;
@Column(nullable = true)
private byte priceReachedNotifications;
@Column(nullable = true)
private byte approximatePriceNotifications;
private boolean notify;
// getters and setters omitted
}

Status.java:

//imports omitted
@Entity
@Table(name = "price_alert_status")
public class Status implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
@Column(name = "status_name")
@NotBlank
private String name;
//getters and setters omitted
}

类型.java:

//imports omitted
@Entity
@Table(name = "price_alert_type")
public class Type implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
@Column(name = "type_name")
@NotBlank
private String name;
//getters and setters omitted
}

存储库:

AlertPosition.java:

//imports omitted
@Repository
public interface AlertRepository extends JpaRepository<Alert, Long> {
}

StatusPositiony.java:

//imports omitted
@Repository
public interface StatusRepository extends JpaRepository<Status, Long> {
}

TypeRepository.java:

//imports omitted
@Repository
public interface TypeRepository extends JpaRepository<Type, Long> {
}

现在,主控制器:

AlertController.java:

@RestController
@RequestMapping("/api")
public class AlertController {
@Autowired
AlertRepository alertRepository;
@Autowired
StatusRepository statusRepository;
@Autowired
TypeRepository typeRepository;
@GetMapping("/alerts")
public List<Alert> getAllAlerts() {
return alertRepository.findAll();
}
@PostMapping("/alert")
public Alert createAlert(@Valid @RequestBody Alert alert) {
return alertRepository.save(alert);
}
@GetMapping("/alert/{id}")
public Alert getAlertById(@PathVariable(value = "id") Long alertId) {
return alertRepository.findById(alertId)
.orElseThrow(() -> new ResourceNotFoundException("Alert", "id", alertId));
}
@PutMapping("/alert/{id}")
public Alert updateAlert(@PathVariable(value = "id") Long alertId,
@Valid @RequestBody Alert alertDetails) {
Alert alert = alertRepository.findById(alertId)
.orElseThrow(() -> new ResourceNotFoundException("Alert", "id", alertId));
alert.setApproximatePriceNotifications(alertDetails.getApproximatePriceNotifications());
alert.setCancelationDate(alertDetails.getCancelationDate());
alert.setNotify(alertDetails.isNotify());
alert.setPrice(alertDetails.getPrice());
alert.setPriceReachedNotifications(alertDetails.getPriceReachedNotifications());
alert.setSendPeriodicEmail(alertDetails.isSendPeriodicEmail());
alert.setUserId(alertDetails.getUserId());
// TODO: how to update Status and Type?
Alert updatedAlert = alertRepository.save(alert);
return updatedAlert;
}
@DeleteMapping("/alert/{id}")
public ResponseEntity<?> deleteAlert(@PathVariable(value = "id") Long alertId) {
Alert alert = alertRepository.findById(alertId)
.orElseThrow(() -> new ResourceNotFoundException("Alert", "id", alertId));
alertRepository.delete(alert);
return ResponseEntity.ok().build();
}
}

所以,我有两个问题:

  • 如何通过POST创建警报并关联现有状态和类型

例如,这将是我的cURL。我试图表明我想将"状态"one_answers"类型"现有对象关联到此新警报,并传递它们各自的ID:

curl -H "Content-Type: application/json" -v -X POST localhost:8080/api/alert -d '{"userId": "1", "price":"20.0", "status": {"id": 0}, "type": {"id": 0}, "sendPeriodicEmail":false,"notify":true}'
  • 与第一个问题一样,如何更新警报,关联新的现有"状态"one_answers"类型"对象

谢谢!

我认为没有现成的方法可以通过单个POST请求实现这一点。我看到大多数时候使用的方法是发出创建Alert的初始请求,然后发出关联Status和Type的后续请求。

您可以在这里查看Spring Data Rest是如何解决问题的:

https://reflectoring.io/relations-with-spring-data-rest/

https://docs.spring.io/spring-data/rest/docs/current/reference/html/#repository-resources.association-资源

不过,我不是Spring Data Rest的忠实粉丝,因为它会迫使你咽下一些东西(比如仇恨(,但是您可以很容易地手动实现相同的方法。

你可能会说,单独调用来设置警报的状态和类型是过分的,因为这两者实际上都是警报的一部分,我可能真的同意。因此,如果你不介意稍微偏离人们通常称之为RESTAPI的刚性(但更像是暴露数据模型的CRUD接口(,那么在警报创建端点中使用AlertTo(带有状态和类型ID(,用这些ID检索状态和类型,并创建最终将存储的警报对象是有意义的。

说了以上所有内容,如果Status和Type只有一个名称,我将避免使用它们。我会在警报本身中有这些名称,而根本没有关系。是的,它可能会占用数据库上更多的空间,但现在磁盘空间几乎不是问题,我猜状态和类型通常是短字符串。

我承认我特别反对这种id名称查找表模式,因为我们的一个项目中有几十个这样的模式,它们只会生成很多无用的代码,并使DB模式复杂化。

最新更新