我有一个实体E1
定义为spring + hibernate为什么多对多的关系不会持久?
@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);
}
}
(E1Repository
和E2Repository
是扩展JpaRepository
@Repository
注释接口并有空的身体)。
,当我通过我的调试器c
方法步骤,我看到最后两行em.refresh
后,无论是e1
和e2
有自己的电视机清除。
基于我对堆栈溢出发现的其他问题,我试图定义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
是实现JpaRepository弹簧创建的Bean。 运行此代码时,插入语句在result
对象(hibernate会将其所有sql命令输出到控制台)的休眠状态下运行,但没有一个用于“match_robot”表。我不应该说,这个段之前,result
是在Hibernate实体生命周期的过渡状态,match
是在持久状态,robot
是在持久状态,result
的match
和robot
属性已设置为match
和robot
分别。
基于堆栈溢出和其他网站的其他问题,我也试图定义匹配变量
@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);
}
您可以在调用'resultRepository.save(result)'之前发布您的代码吗?'为了让您的对象网在开始保存时看起来像是什么样子?更好的整个方法?这个方法还是包含用@ Transactional注解的类? –
@ ansgar-schulte我遗漏了方法的前面部分,因为除了创建和保存'Robot'对象并给出404(如果match对象为null)之外,它没有与'Robot'或“匹配”。我会继续并添加它。 –
*当我在调试器中通过c方法时,我发现在最后两行em.refresh行之后,e1和e2都清除了它们的集合。*:当然,它们是,因为您刷新它们而没有刷新你刚刚做出的改变。你为什么刷新?为什么你重新保存管理实体?所有这些重新保存和刷新都是无用的,甚至是适得其反的。阅读http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#refresh(java.lang.Object):*刷新...覆盖对实体所做的更改(如果有的话)。* 。 –