我有一个Group
类,可以容纳许多项目:
@Entity
@Table(name = "groups")
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private Integer version;
@OneToMany(
mappedBy = "group",
fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
private List<Project> projects;
public void addProject(Project project) {
if (projects == null) {
projects = new ArrayList<>();
}
this.projects.add(project);
project.setGroup(this);
}
public void removeProject(Project project) {
if (projects == null || projects.size() == 0) {
return;
}
this.projects.remove(project);
project.setGroup(null);
}
}
和Project
类:
@Entity
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
private Group group;
}
由于Project
类中未设置级联类型,因此以下代码在运行时将引发错误:
Group group = new Group(123);
Project project = new Project("projectName");
group.addProject(project);
projectRepo.save(project);
java.lang.IllegalStateException:org.hibernate.TransientPropertyValueException:对象引用了一个未保存的临时实例-在刷新之前保存该临时实例。
但是当我在测试方法中运行相同的代码时,它通过了!组和项目均已保存。这是我的测试类配置:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationLauncher.class)
测试方法在@Test旁边没有任何特殊注释。当我运行它时,hibernate生成3条sql语句:
在测试中和运行应用程序时都使用了H2数据库。
这里的魔力是什么?