SpringBoot Test JPA got "no session" exception when FetchType=Lazy

Viewed 362

I'm junit testing inside the below function:

    @Test
    public void testQueryUser(){
        User user1 = userRepository.findById(12L).orElse(null);
        assertThat(user1)
       .hasFieldOrPropertyWithValue("username", "adam");
    }

The below is my domain class User:

@Entity
@Table(name = "sys_user")
@Data
@NoArgsConstructor
@AllArgsConstructor
@DynamicUpdate
public class User extends BaseEntity implements Serializable{

    @Id
    @Column(name = "user_id")
    @NotNull(groups = {Update.class})
    @Null(groups = {Create.class})
    @ApiModelProperty(value = "ID", hidden = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToMany(fetch = FetchType.EAGER)
    @ApiModelProperty(value = "user_role")
    @JoinTable(name = "sys_users_roles",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "role_id")})
    private Set<Role> roles;

    @ManyToOne
    @JoinColumn(referencedColumnName = "dept_id")
    private Dept dept;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "sys_user_jobs",
            joinColumns = {@JoinColumn(name="user_id", referencedColumnName = "user_id")},
    inverseJoinColumns = {@JoinColumn(name = "job_id", referencedColumnName = "job_id")})
    private Set<Job> jobs;

    @NotBlank
    @Column(unique = true)
    @ApiModelProperty(value = "username")
    private String username;
}

Got the below error message as expected:

java.lang.AssertionError: Expecting User(id=12, roles=[], dept=null, jobs=[], username=adam) to have a property or a field named "username" with value "adam" but value was: "paul"

But when switching @ManyToMany(fetch = FetchType.EAGER) back to @ManyToMany(fetch = FetchType.LAZY) inside domain class I got

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.adminsys.modules.system.domain.User.roles, could not initialize proxy - no Session

My questions are:

  1. I'm only testing the field username but why JUnit is looking into field roles?
  2. Why no session?
  3. What's the best practice for my scenario?
0 Answers
Related