gpt4 book ai didi

spring-boot - spring boot REST Api 中的一对多关系

转载 作者:行者123 更新时间:2023-12-05 02:46:14 25 4
gpt4 key购买 nike

我正在使用 spring boot 创建 REST API。在此 API 中,check-inGuests 之间存在一对多关系。我创建了一个用于 checkin 的 Controller ,并使用了 spring JPA 的保存功能。保存方法同时更新checkinguest 表,但对于guest 表,check-in guests 表中的外键 没有被添加而是显示为空。请有人帮助我。我需要同时创建 guest 和签到。

签到模型

@Data
@Entity
public class Checkin {

@Id
private Long id;

private Integer no_of_guests;

@OneToMany(mappedBy = "checkin", cascade = CascadeType.ALL)
private List<Guest> guests;
}

客人模型

@Data
@Entity
public class Guest {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long guest_id;

private String name;

private String mobile_no;

private String address;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "guest_checkin_id", nullable = false )
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Checkin checkin;

}

签到 Controller

@RestController
@RequestMapping("/checkin")
public class CheckinController {

private final CheckinRepository checkinRepo;
private final GuestRepository guestRepo;

public CheckinController(CheckinRepository checkinRepo,GuestRepository guestRepo){
this.checkinRepo = checkinRepo;
this.guestRepo = guestRepo;
}

@PostMapping("/add")
ResponseEntity<Object> roomCheckin(@RequestBody Checkin checkin){
if(checkinRepo.save(checkin) != null){
return ResponseEntity.accepted().body("Checkin Successfull");
}
return ResponseEntity.unprocessableEntity().body("Failed to Checkin");
}
}

最佳答案

使用实体类作为 View 模型类可能有点棘手,尤其是在 CheckinGuest .

让我们从验证实体类和存储库是否如描述的那样工作开始。为了进行测试运行,我必须在 Checkin 类中为 id 字段添加 @GeneratedValue

其他变化:

为了验证代码,我在下面添加了一个测试类CheckinRepositoryTest


如前所述,使用实体类作为 View 模型类可能很棘手,因此下一步将引入两个新的 View 模型类:CheckinVMGuestVM,以及一个新的服务类 GuestService,它将负责保存 CheckinGuest 实例。代码如下所示。

请注意,我只添加了 GuestService 类的框架,我将其留给您来实现。 CheckinRepositoryTest 中的代码说明了如何实现它。

有了 View 模型类,@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 应该被移除。


所有部分都启动并运行后,您应该向新的 View 模型类添加验证,以及一些验证行为的集成测试。如果您正在遵循 TDD,您将按自己的方式添加测试。

您还应该查看您的 Controller 方法并为成功和失败情况使用适当的状态代码。


客舱

package no.mycompany.myapp.misc;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;

@Getter
@Setter
@Entity
public class Guest {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long guest_id;

private String name;

private String mobile_no;

private String address;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "guest_checkin_id", nullable = false)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Checkin checkin;
}

GuestVM 类

package no.mycompany.myapp.misc;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class GuestVM {

private long id;
private String name;
private String mobile_no;
private String address;

public GuestVM(Guest guest) {
this.id = guest.getGuest_id();
this.name = guest.getName();
this.mobile_no = guest.getMobile_no();
this.address = guest.getAddress();
}
}

报到类

package no.mycompany.myapp.misc;

import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Getter
@Setter
@Entity
public class Checkin {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private Integer no_of_guests;

@OneToMany(mappedBy = "checkin", cascade = CascadeType.ALL)
private Set<Guest> guests = new HashSet<>();
}

CheckinVM 类

package no.mycompany.myapp.misc;

import lombok.Getter;
import lombok.Setter;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.stream.Collectors;

@Getter
@Setter
@NoArgsConstructor
public class CheckinVM {

private long id;
private List<GuestVM> guests;

public CheckinVM(Checkin checkin) {
this.id = checkin.getId();
this.guests = checkin.getGuests().stream().map(GuestVM::new).collect(Collectors.toList());
}
}

checkin 存储库

package no.mycompany.myapp.misc;

import org.springframework.data.jpa.repository.JpaRepository;

public interface CheckinRepository extends JpaRepository<Checkin, Long> { }

CheckinRepositoryTest

package no.mycompany.myapp.misc;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;

@DataJpaTest
public class CheckinRepositoryTest {

@Autowired
TestEntityManager testEntityManager;

@Autowired
CheckinRepository checkinRepository;

@Test
public void test() {

// create instances
var checkinInDb = new Checkin();
var guestInDb = new Guest();

// add relations
guestInDb.setCheckin(checkinInDb);
checkinInDb.getGuests().add(guestInDb);

// save check-in
checkinRepository.save(checkinInDb);

// verify that check-in has one guest
var checkin = testEntityManager.find(Checkin.class, checkinInDb.getId());
assertThat(checkin.getGuests().size()).isEqualTo(1);

// verify that guest is connected to a check-in
var guest = testEntityManager.find(Guest.class, guestInDb.getGuest_id());
assertThat(guest.getCheckin()).isNotNull();
}
}

CheckinService 类:我把这个留给你去实现

package no.mycompany.myapp.misc;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CheckinService {

private final CheckinRepository checkinRepository;

public CheckinVM saveCheckin(CheckinVM checkin) {
return null; // TODO: implement this
}
}

Controller 类

package no.mycompany.myapp.misc;

import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/checkin")
@RequiredArgsConstructor
public class CheckinController {

private final CheckinService checkinService;

@PostMapping("/add")
ResponseEntity<Object> roomCheckin(@RequestBody CheckinVM checkin) {
if (checkinService.saveCheckin(checkin) != null) {
return ResponseEntity.accepted().body("Checkin Successful");
}
return ResponseEntity.unprocessableEntity().body("Failed to Checkin");
}
}

关于spring-boot - spring boot REST Api 中的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65612311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com