I'm wondering how @Transactional works with Spring Data JPA / Hibernate on test methods. I searched some explanations on the web but it still seems obscure.
Below is the code I'm using:
Member.java
@Entity
@Table(name = "MEMBER")
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
String firstname;
String lastname;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(
name = "MEMBER_ROLE",
joinColumns = @JoinColumn(name = "member_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles = new HashSet<Role>();
// Getters...
// Setters...
}
Role.java
@Entity
@Table(name = "ROLE")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String description;
public Role(String name, String description) {
this.name = name;
this.description = description;
}
@ManyToMany(mappedBy = "roles", cascade = CascadeType.ALL)
private Set<User> users = new HashSet<User>();
public void addUser(User user) {
users.add(user);
user.getRoles().add(this);
}
// Getters...
// Setters...
}
MemberRepositoryTest.java
@SpringBootTest
public class MemberRepositoryTest {
@Autowired
private MemberRepository memberRepository;
@Test
@Transactional
//@Commit // When @Commit is uncommented, the relation is saved in the database
public void testSave() {
Member testMember = new Member();
testMember.setFirstname("John");
testMember.setLastname("Doe");
Role role1 = new Role("ROLE_USER", "The role of for basic users");
Role role2 = new Role("ROLE_ADMIN", "The role of for admin users");
testMember.getRoles().add(role1);
testMember.getRoles().add(role2);
this.memberRepository.save(testMember);
// The 2 roles are well in the set
System.out.println("********" + this.memberRepository.findById(1).get().getRoles().toString());
}
}
- The thing is that when I use @Transactional alone without @Commit, only the user and the role entries are created. The table
MEMBER_ROLE
is created but empty (no entry): then:n
@ManyToMany unidirectional relation is not saved. - When using
@Commit
, everything works properly: there are 2 entries corresponding to the role of the John Doe user.
Here are my questions:
How does CrudRepository.save(...) work under the hood with @Transactional and why using this annotation alone does a "partial save"? We should expect that without @Commit
nothing is committed to the database (and everything is roll backed).
Is it a good practice to use @Transactional
on test methods?