我正在尝试实现@ManyToMany关系,但是没有填充我的联接表。我的应用程序将一堆Competition对象建模为Competitor对象。有一组竞争对手。在该组中,每个竞争者都将彼此配对以组成竞赛。因此,每个竞赛都可以有一个竞赛对象列表。每个参赛者可以参加多个比赛。

实体对象

比赛看起来像这样:

@Entity
@Table(name = "competition")
public class Competition implements java.io.Serializable {

    @Id
    @GeneratedValue
    private int competitionId;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "competition_competitors", joinColumns = @JoinColumn(name = "competitionId"), inverseJoinColumns = @JoinColumn(name = "competitorId"))
    private Set<Competitor> competitors = new TreeSet<Competitor>();

            . . .


我的竞争对手对象看起来像这样:

@Entity
@Table(name = "competitor")
public class Competitor implements Comparable<Competitor>, java.io.Serializable {

    @Id
    @GeneratedValue
    private int competitorId;

    @ManyToMany(mappedBy = "competitors", cascade = CascadeType.ALL)
    private Set<Competition> competitions = new TreeSet<Competition>();

            . . .


CompetitionService方法

@Override
@Transactional(readOnly = false)
public Competition createCompetition(League league, Competitor competitor1, Competitor competitor2) {
    Competition competition = getCompetitionDAO().create(league);
    competition.add(competitor1);
    competition.add(competitor2);
    this.competitionDao.saveOrUpdate(competition);
    return competition;
}


CompetitionDAO方法

@Override
@Transactional(readOnly = false)
public void saveOrUpdate(Competition competition) {
    if (competition != null) {
        Session session = getCurrentSession();
        try {
            session.saveOrUpdate(competition);
        } catch (Exception exception) {
            throw new AppException(exception);
        }
    }
}


申请代码

此代码应创建比赛并将其持久化。它曾经做到这一点,但是我在某处打破了它,并且不再将任何内容保存到联接表{competition_competitors}中。

@Transactional(readOnly = false)
private void createLeague(LeagueData leagueData) {

    User user = createAccount( ... );
    League league = createLeague(user, leagueData.getLeagueName());

    for (int index = 0; index < leagueData.getCompetitorNames().length; index++) {
        Competitor competitor = this.serviceProvider.getCompetitorService().find(league, leagueData.getCompetitorNames()[index]);
        if (competitor == null) {
            competitor = createCompetitor(league, leagueData.getCompetitorNames()[index], leagueData.getCompetitorDescription()[index]);
        }
        this.serviceProvider.getCompetitionService().createCompetition(league, competitor);
    }
}


问题:关于为什么在运行应用程序时不填充联接表的任何想法?该应用程序代码运行无误。我不明白为什么单元测试可以正常工作并正确填充联接表,但是类似的应用程序代码却不能。

最佳答案

如果您看不到MySQL Workbench内出现的值但您的单元测试正在通过,那是因为单元测试完成后Spring会自动回滚事务。因此,如果您可以在提交事务的确切时间立即刷新MySQL Workbench,那么在回滚事务并丢失这些值之前,您将看到大约0.2毫秒的值。

您的联接表正在工作,否则您的断言将失败。

关于java - Hibernate @ManyToMany-未填充联接表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23666732/

10-13 05:30