春季启动REST CRUD-如何发布具有一对一关系的实体?

时间:2018-07-21 12:31:23

标签: java hibernate spring-boot jpa crud

我有一个非常简单的域模型:“警报”具有一个“类型”和一个“状态”。

这是我的模式:

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
}

Type.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
}

存储库:

AlertRepository.java:

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

}

StatusRepository.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。我试图表明我想将现有对象的“状态”和“类型”关联到此新警报,并传递它们各自的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}'
  • 像第一个问题一样,如何将新的现有“状态”和“类型”对象相关联来更新警报?

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为,对于单个POST请求,没有现成的方法可以实现这一目标。我看到的大部分时间都使用的方法是发出一个初始请求来创建警报,然后发出请求来关联“状态”和“类型”。

您可以在此处查看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-resource

尽管我不是Spring Data Rest的最大粉丝,因为它会迫使某些东西(例如仇恨)下垂 ,但是您可以轻松地手动实现相同的方法。

您可能会争辩说,单独发出呼叫以设置警报的状态和类型,这实际上是警报的一部分,我可能会同意,这是过大的选择。因此,如果您不介意稍微偏离人们通常所说的REST API(但更像是暴露数据模型的CRUD接口)的刚性,则可以在警报中使用AlertDto(带有状态和类型ID)创建端点,使用这些ID检索状态和类型,并创建最终将存储的Alert对象。

上面已经说完了,如果它们都有一个名称,我将避免使用Status和Type表。我将在Alert本身中使用此名称,并且完全没有关系。是的,它可能会占用数据库更多的空间,但是如今磁盘空间已不再是一个问题,我猜测状态和类型通常是短字符串。

我承认我对这种id名称查找表模式特别有偏见,因为在我们的一个项目中我们有数十个这样的id-name查找表模式,它们除了生成大量无用的代码并使DB模式复杂化之外什么也不做。