繁体   English   中英

Spring + Hibernate为什么不保持多对多关系?

[英]spring+hibernate why is many-to-many relationship not persisted?

我有一个实体E1定义为

@Entity
public class E1 {
    @Id
    @GeneratedValue
    public long id;
    @ManyToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(
            name="e1_e2",
            joinColumns = @JoinColumn(name = "e2_id"),
            inverseJoinColumns = @JoinColumn(name = "e1_id")
    )
    public Set<E2> e2s = new HashSet<>();
}

实体E2定义为

@Entity
public class E2 {
    @Id
    @GeneratedValue
    public long id;
    @ManyToMany(mappedBy = "e2s")
    public Set<E1> e1s = new HashSet<>();
}

和控制器定义为

@RestController
@RequestMapping("/")
public class C1 {
    private final E1Repository e1Repository;
    private final E2Repository e2Repository;

    @PersistenceContext
    EntityManager em;

    @Autowired
    public C1(E1Repository e1Repository, E2Repository e2Repository) {
        this.e1Repository = e1Repository;
        this.e2Repository = e2Repository;
    }

    @Transactional
    @RequestMapping(method = POST)
    public void c(){
        E1 e1 = new E1();
        E2 e2 = new E2();

        e1Repository.save(e1);
        e2Repository.save(e2);

        em.refresh(e1);
        em.refresh(e2);

        e1.e2s.add(e2);
        e2.e1s.add(e1);

        e1Repository.save(e1);
        e2Repository.save(e2);

        em.refresh(e1);
        em.refresh(e2);
    }

}

E1RepositoryE2Repository@Repository延伸注释接口JpaRepository和具有空体)。

当我在调试器中逐步执行c方法时,我看到在最后两行em.refresh行之后, e1e2的集合都被清除了。

根据我在Stack Overflow上发现的其他问题,我尝试将E2定义为

@Entity
public class E2 {
    @Id
    @GeneratedValue
    public long id;
    @ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(
            name="e1_e2",
            inverseJoinColumns = @JoinColumn(name = "e2_id"),
            joinColumns = @JoinColumn(name = "e1_id")
    )
    public Set<E1> e1s = new HashSet<>();
}

但这没有帮助。

原始问题 (在尝试测试上述简化案例之前),我定义了一个类似于以下内容的Robot类:

@Entity
class Robot{
    @Id
    @GeneratedValue
    private long id;

    @ManyToMany(mappedBy="robots")
    private Set<Match> matches = new HashSet<>();
}

和一个类Match类似

@Entity
class Robot{
    @Id
    @GeneratedValue
    private long id;
    @ManyToMany(cascade={CascadeType.Persist,CascadeType.Merge})
    @JoinTable(
        name = "match_robot",
        joinColumns = {@JoinColumn(name = "Match_id")},
        inverseJoinColumns = {@JoinColumn(name = "Robot_id")}
)
private Set<Robot> robots = new HashSet<>();

和定义的类Result类似

@Entity
public class Result {
    @Id
    @GeneratedValue
    private long id;

    @ManyToOne(optional = false)
    private Match match;

    @ManyToOne(optional = false)
    @NotNull(groups = {Default.class, Creating.class})
    private Robot robot;
}

并尝试如下保存该关系:

resultRepository.save(result);
match.getRobots().add(result.getRobot());
result.getRobot().getMatches().add(match);
robotRepository.save(result.getRobot());
matchRepository.save(match);
entityManager.refresh(result);
entityManager.refresh(result.getRobot());
entityManager.refresh(match);

其中*Repository是由spring创建的实现JpaRepository的bean。 当运行此代码时,休眠对象将为result对象运行一个插入语句(休眠将其所有sql命令输出到控制台),而“ match_robot”表则不会运行。 我不应该在此代码段之前将result为休眠状态,以使其处于休眠状态,而match处于持久状态, robot处于持久状态,并且resultmatchrobot属性已设置为matchrobot分别。

基于Stack Overflow和其他网站上的其他问题,我还尝试将matchs变量定义为

@ManyToMany(cascade = CascadeType.PERSIST)
@JoinTable(
        name = "match_robot",
        inverseJoinColumns = {@JoinColumn(name = "Match_id")},
        joinColumns = {@JoinColumn(name = "Robot_id")}
)
private Set<Match> matches = new HashSet<>();

这没有帮助。 除此之外,我看到的唯一建议是确保多对多关系中的两个实体在持久存在之前彼此一致,但是据我所知,我在这里这样做。

如何保持这种关系?

编辑:上下文的完整方法:

@Transactional
@RequestMapping(value = "/{match:[0-9]+}/results", method = RequestMethod.POST)
public ResultResource createResult(@PathVariable Match match,
                                   @Validated(Result.Creating.class)
                                   @RequestBody Result result) {
    if (match == null) throw new ResourceNotFoundException();

    result.setScorecard(scorecardRepository
            .findById(result.getScorecard().getId()));
    if (result.getScorecard() == null) {
        throw new ScorecardDoesNotExistException();
    }

    result.setMatch(match);

    //remove null scores
    result.getScores().removeIf(
            fieldResult -> fieldResult.getScore() == null
    );

    //replace transient robot with entity from database
    Robot existingRobot = robotRepository
            .findByNumberAndGame(result.getRobot().getNumber(),result.getRobot().getGame());
     if (existingRobot == null) { //create new robot
        //find team for this robot
        Team existingTeam = teamRepository
                .findByNumberAndGameType(
                        result.getRobot().getNumber(),
                        result.getScorecard().getGame().getType());
        if (existingTeam == null) {
            Team team = new Team();
            team.setNumber(result.getRobot().getNumber());
            team.setGameType(result.getMatch().getEvent().getGame().getType());
            team.setDistrict(result.getMatch().getEvent().getDistrict());
            teamRepository.save(team);
            result.getRobot().setTeam(team);
        }
    else result.getRobot().setTeam(existingTeam);
             result.getRobot().setGame(result.getMatch().getEvent().getGame());

        robotRepository.save(result.getRobot());
        entityManager.refresh(result.getRobot());
    } else result.setRobot(existingRobot);
    List<Robot> all = robotRepository.findAll();

    //replace transient FieldSections with entities from database
    //todo: reduce database hits
    //noinspection ResultOfMethodCallIgnored
    result.getScores().stream()
          .peek(fieldResult -> fieldResult.setField(
                  fieldSectionRepository.findByIdAndScorecard(
                          fieldResult.getField().getId(),
                          result.getScorecard())))
              .peek(fieldResult -> {
              if (fieldResult.getField() == null)
                  throw new ScoresDoNotExistException();
          })
          .forEach(fieldResult->fieldResult.setResult(result));


    if (!result.scoresMatchScorecardSections()) {
        throw new ScoresDoNotMatchScorecardException();
    }

    if (!result.allMissingScoresAreOptional()) {
        throw new RequiredScoresAbsentException();
    }

    if (!result.gameMatchesScorecard()) {
        throw new GameDoesNotMatchScorecardException();
    }

    resultRepository.save(result);
    match.getRobots().add(result.getRobot());
    result.getRobot().getMatches().add(match);
    robotRepository.save(result.getRobot());
    matchRepository.save(match);
    entityManager.refresh(result);
    entityManager.refresh(result.getRobot());
    entityManager.refresh(match);
    return new ResultResourceAssembler().toResource(result);
}

JpaRepository.save()不会将更改刷新到数据库。 必须使用JpaRepository.flush()JpaRepository.saveAndFlush()刷新更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM