JPA OneToMany只保留一个

时间:2017-01-13 22:46:58

标签: java hibernate jpa spring-data-jpa

我有这段代码:

@Table(name = "Prize")    
public class Prize {
    @Id
    @Column(
        nullable = false,
        unique = true
    )
    private int id;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @Fetch(FetchMode.JOIN) 
    private Set<TicketNumber> numbers;

}

@Table(name = "TicketNumber") 
public class TicketNumber {
    @Id
    @Column(
        nullable = false,
        unique = true
    )
    private int id;
}

这创建了一个名为Prize_TicketNumber的连接表,其中包含两个字段(Prize_id和TicketNumber_id),但是当我保存一个包含许多数字的奖品时,在该表中只插入一条记录。有谁知道为什么?

编辑:这是插入的代码。存储库是简单的JpaRepositories。

Prize prize = prizeRepository.findById(prizeId);
if(prize == null) return;
List<TicketNumber> winners = ticketNumberRepository.findByPrizeId(fixedPrize.getId());
if (winners != null && !winners.isEmpty()) {
    for (TicketNumber winner : winners) {
        winner.setWinner(false);
        TicketNumber t = ticketNumberRepository.save(winner);
    }
    raffleNumberRepository.flush();
}
prize.getTicketNumbers().clear();
for (String ticketId : ids) {
    TicketNumber ticketNumber = ticketNumberRepository.findOne(ticketId);
    if (ticketNumber != null) {
        ticketNumber.setWinner(true);
        prize.getTicketNumbers().add(raffleNumber);
    }
}
prize.setNumbersAssigned(true);
prizeRepository.saveAndFlush(prize);

1 个答案:

答案 0 :(得分:-2)

一对多关联不应该需要连接表。在一对多关联中,孩子应该保留父母的id。

看起来你错过了你孩子的父ID,而hibernate假设这是一个多对多关联,然后创建连接表。