Java 如何在单个junit测试之前以编程方式设置h2数据库?
我有一个带有h2数据库的简单spring启动应用程序 我想编写单元测试,以确认我选择的注释的行为符合预期 我的代码如下:Java 如何在单个junit测试之前以编程方式设置h2数据库?,java,spring,spring-boot,jpa,h2,Java,Spring,Spring Boot,Jpa,H2,我有一个带有h2数据库的简单spring启动应用程序 我想编写单元测试,以确认我选择的注释的行为符合预期 我的代码如下: import java.util.List; import javax.persistence.*; import lombok.*; @NoArgsConstructor //otherwise there are errors on delete @AllArgsConstructor @RequiredArgsConstructor @Entity @Table(nam
import java.util.List;
import javax.persistence.*;
import lombok.*;
@NoArgsConstructor //otherwise there are errors on delete
@AllArgsConstructor
@RequiredArgsConstructor
@Entity
@Table(name = "pupils")
public class Pupil {
@Id
private long id;
@NonNull
private String name;
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
name = "pupils_subjects",
joinColumns = @JoinColumn(name = "pupil_id"),
inverseJoinColumns = @JoinColumn(name = "subject_id"))
@OrderColumn(name = "id")
private List<Subject> subjects;
}
我明白了
因此,我需要将设置放在不同的会话中。我该怎么做
import java.util.List;
import javax.persistence.*;
import lombok.*;
@NoArgsConstructor
@RequiredArgsConstructor
@Entity
@Table(name = "subjects")
public class Subject {
@Id
private long id;
@NonNull
private String name;
@ManyToMany
private List<Subject> subjects;
}
import org.springframework.data.repository.CrudRepository;
public interface PupilRepository extends CrudRepository<Pupil, Long> {}
public interface SubjectRepository extends CrudRepository<Subject, Long> {}
@ExtendWith(SpringExtension.class)
@DataJpaTest
public class BehaviourTest {
@Autowired
PupilRepository pupilRepo;
@Autowired
SubjectRepository subjectRepo;
@Test
public void testAddTwoSubjectsThenPupil() {
//setup
Subject math = new Subject(0, "Maths");
Subject english = new Subject(1, "English");
subjectRepo.save(math);
subjectRepo.save(english);
//actual test
math = new Subject(0, "Maths");
english = new Subject(1, "English");
Pupil alice = new Pupil(0, "alice", Arrays.asList(math, english));
pupilRepo.save(alice);
assertThat(pupilRepo.count()).isEqualTo(1);
assertThat(subjectRepo.count()).isEqualTo(2);
}
org.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session : [com.example.petstore.stacko.jpa0.Subject#1]; nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.example.petstore.stacko.jpa0.Subject#1]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:400)
...