Spring在创建父对象时如何添加子实体

时间:2018-12-19 09:54:37

标签: spring hibernate

所以我有一个showTime实体,它与Seating有一对多的关系。因此,我需要做的是在创建showTime时自动向该showTime添加x个座位。我不确定该怎么做。

@Entity
public class ShowTime {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name="movie_id")
    private Movie movie;

    @ManyToOne
    @JoinColumn(name="saloon_id")
    private Saloon saloon;

    private String date;

    private String time;

    @OneToMany(cascade=CascadeType.ALL,mappedBy = "showTime")
    @JsonIgnore
    private List<Seating> SeatingList;
    //getters setters

    Seating class

    @Entity
    public class Seating {

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

        @ManyToOne
        @JoinColumn(name="showtime_id")
        private ShowTime showTime;

        private int seatNo;

        private boolean isTaken=false;


    }
}

1 个答案:

答案 0 :(得分:0)

您已经使用CascadeType.ALL映射了座位表,这会使事情变得更容易。

在坚持ShowTime之前,您应该创建必要的座位,并确保正确设置了两者之间的关系,然后坚持ShowTime

例如持续的showTime和1个席位:

ShowTime showTime = new ShowTime();
//code to setup other showTime attributes
Seating seat = new Seating();
showTime.getSeatingList().add(seat);
seat.setShowTime(showTime);
session.persist(showTime);

应该这样做。