【发布时间】:2018-05-07 14:20:03
【问题描述】:
我正在创建一个 Spring Boot 应用程序并使用它在JpaRepository 接口中构建来存储我的实体。我有以下两个实体(为了便于阅读,删除了 getter 和 setter):
个人资料实体
@Entity
public class Profile {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany(mappedBy = "profileOne", orphanRemoval = true)
private List<Match> matchOnes;
@OneToMany(mappedBy = "profileTwo", orphanRemoval = true)
private List<Match> matchTwos;
}
匹配实体
@Entity
@Table(uniqueConstraints={
@UniqueConstraint(columnNames = { "profileOne_id", "profileTwo_id" })
})
public class Match {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@ManyToOne
@JoinColumn(name = "profileOne_id")
private Profile profileOne;
@ManyToOne
@JoinColumn(name = "profileTwo_id")
private Profile profileTwo;
}
为了理解JpaRepository 的行为,我编写了以下单元测试。
@RunWith(SpringRunner.class)
@DataJpaTest
public class IProfileDaoTest {
@Autowired
private IProfileDao profileDao; //This class extends JpaRepository<Profile, long>
@Autowired
private IMatchDao matchDao; //This class extends JpaRepository<Match, long>
@Test
public void saveProfileTest() throws Exception {
@Test
public void profileMatchRelationTest() throws Exception {
//Test if matches stored by the IMatchDao are retrievable from the IProfileDao
Profile profileOne = new Profile("Bob"),
profileTwo = new Profile("Alex");
profileDao.saveAndFlush(profileOne);
profileDao.saveAndFlush(profileTwo);
matchDao.saveAndFlush(new Match(profileOne, profileTwo));
profileOne = profileDao.getOne(profileOne.getId());
Assert.assertEquals("Match not retrievable by profile.", 1, profileOne.getMatchOnes().size());
}
}
现在我预计匹配项会出现在配置文件实体中,但事实并非如此。我还尝试将CascadeType.ALL 添加到匹配实体中的@ManyToOne 注释,并将FetchType.EAGER 添加到配置文件实体中的@OneToMany 注释。
是否可以通过在 profileDao 中请求配置文件来获取 matchDao 保存的匹配项?或者我应该找到具有单独功能的配置文件的匹配项?
【问题讨论】:
-
您是否尝试过(在您的测试中)在执行 getOne 之前保留匹配和更新的配置文件?
-
JpaRepository没有持久化方法。相反,您可以致电saveAndFlush()或flush()来保存您的更改。在这种情况下,我使用saveAndFlush()来确保存储所有实体。 -
坚持我的意思是执行 saveAndFlush,对不起。
标签: java jpa spring-data-jpa