In my Spring 4 project with Hibernate 5 and Java-based configuration I keep facing exception "could not initialize proxy - no Session " every time Jackson tries to serialize my entity with a lazy collection. It seems Jackson fails to check if collection is lazy and triggers loading which generates the exception. How do I make Jackson avoid serialization of every lazy-loaded collection on every @Entity-class and thus avoid constant exceptions and fails with "no Session"? The simplest working solution. I've read many approaches neighter of which really solves this problem for me. Any help will be appreciated (not for Spring Boot!). Some code snippet:
@Data
@Entity
@ToString(exclude="questions")
@Table(name = "theme")
public class Theme {
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "id")
private Long id;
@Column(name = "title")
private String title;
@JsonInclude(JsonInclude.Include.NON_NULL)
@OneToMany // LAZY by default
@JoinColumn(name = "theme")
private List<Question> questions;// = new ArrayList<>();
}
DAO
public interface ThemeDAO extends CrudRepository<Theme, Long> {
List<Theme> findAll();
}
Exception goes here (in controller):
ObjectMapper objectMapper = new ObjectMapper();
result = objectMapper.writeValueAsString(theme);