【发布时间】:2021-05-16 01:20:50
【问题描述】:
如何保存一个嵌套了另一个实体的实体?
回购
public interface ReservationRepository extends JpaRepository<Reservation, Integer> {
Optional<Reservation> findReservationBySection_SectionId(int id);
}
服务
@Service
public class ReservationService {
private final Logger logger = LoggerFactory.getLogger(getClass().getName());
@Autowired
private ReservationRepository reservationRepository;
@Autowired
private SectionRepository sectionRepository;
@Autowired
private UserRepository userRepository;
public Reservation addReservation(Reservation reservation) {
Reservation newReservation = new Reservation();
newReservation.setCount(reservation.getCount());
newReservation.setCustom_section_name(reservation.getCustom_section_name());
newReservation.setFrom_time(reservation.getFrom_time());
newReservation.setTo_time(reservation.getTo_time());
newReservation.setSection(sectionRepository.getOne(reservation.getSection().getSectionId()));
newReservation.setUser(userRepository.getOne(reservation.getUser().getUserId()));
logger.info(newReservation.toString());
return reservationRepository.save(newReservation);
}
}
用户实体
User
@Id
@GeneratedValue
@Column(name = "user_id")
private int userId;
@Column(name = "name")
private String name;
@Column(name="email", unique = true)
private String email;
@JsonIgnore
@Column(name = "password")
private String password;
@Column(name = "phone")
private String phone;
@Column(name = "expiration_date")
private Timestamp expirationDate;
部分实体
Section
@Id
@GeneratedValue
@Column(name = "section_id")
private int sectionId;
@Column(name = "section_name")
private String sectionName;
@OneToOne
@JoinColumn(name="room_id")
private Section roomId;
预订实体
@Id
@GeneratedValue
@Column(name = "reservation_id")
private int reservationId;
@ManyToOne
@MapsId("section_id")
@JoinColumn(name = "section_id")
private Section section;
@ManyToOne
@MapsId("user_id")
@JoinColumn(name = "user_id")
private User user;
@Column(name = "count")
private int count;
@Column(name = "custom_section_name")
private String custom_section_name;
@Column(name = "from_time")
private Timestamp from_time;
@Column(name = "to_time", unique = true)
private Timestamp to_time;
预期结果:
实际结果:
SQL 数据库表的 section_id 和 user_id 不为空,因为它们的表中有主键。 如果需要,将提供更多信息。
【问题讨论】:
标签: spring spring-boot jpa spring-data-jpa crud