所以,我有 2 个实体:
房间:
@Entity
@Table(name = "rooms")
public class Room
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String type;
private String image;
private double price;
@Column(columnDefinition = "TEXT")
private String description;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "guest_id", referencedColumnName = "id")
private Guest guest_id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "guest_name", referencedColumnName = "name")
private Guest guest_name;
嘉宾:
@Entity
@Table(name = "guests")
public class Guest
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String phone_num;
private String email;
private LocalDate check_in_date;
private LocalDate check_out_date;
@OneToOne
@JoinColumn(name = "room_id", referencedColumnName = "id")
private Room room_id;
正如您在 Room 中看到的,有 2 个外键引用 Guest 中的 id 和 name 字段,而 Guest 中有 1 个外键引用 Room 中的 id 字段。
在我的控制器中,有一个方法应该更新我的客人表中的条目:
@PostMapping("/update/{id}")
public String updateGuest(@PathVariable Long id, @ModelAttribute("guest") Guest guest)
{
Guest existingGuest = guestRepository.findById(id).get();
existingGuest.setName(guest.getName());
existingGuest.setPhone_num(guest.getPhone_num());
existingGuest.setEmail(guest.getEmail());
existingGuest.setCheck_in_date(guest.getCheck_in_date());
existingGuest.setCheck_out_date(guest.getCheck_out_date());
guestRepository.save(guest);
return "redirect:/guests/";
}
它在我拥有外键之前就可以工作,但由于现在字段之间存在连接,我认为我还应该更新 rooms 表内的字段。但老实说我很不确定该怎么做。
我想我应该在存储库中创建一个类似这样的方法:
@Repository
public interface RoomRepository extends JpaRepository<Room, Long>
{
@Query("Select g From rooms g Where g.guest_id = :guestId")
List<Room> findGuestById(@Param("guestId") String guestId);
}
我的想法正确吗?
提前非常感谢!
如果客人姓名发生变化,确保相应房间的 guest_name 字段更新以保持两个实体之间的数据一致性至关重要。更新客人信息时,重要的是要验证您是否正在修改现有的客人实体,而不是无意中创建新的客人记录。
你需要修改控制器方法,来处理这些注意事项
@PostMapping("/update/{id}")
public String updateGuest(@PathVariable Long id, @ModelAttribute("guest") Guest guest) { 访客现有访客 = guestRepository.findById(id).orElse(null);
if (existingGuest != null) {
existingGuest.setName(guest.getName());
existingGuest.setPhone_num(guest.getPhone_num());
existingGuest.setEmail(guest.getEmail());
existingGuest.setCheck_in_date(guest.getCheck_in_date());
existingGuest.setCheck_out_date(guest.getCheck_out_date());
// Update the room if needed
Room room = existingGuest.getRoom_id();
if (room != null) {
room.setGuest_id(existingGuest);
// You may need to update other room attributes as well, depending on your logic
roomRepository.save(room);
}
guestRepository.save(existingGuest);
}
return "redirect:/guests/";}
Ceate Interface RoomRepository 扩展了 JpaRepository 并创建了一个通过客人 ID 查找房间的方法。 我想这对你会有帮助。谢谢你。