2
I’m not getting Lazy Load to work in Spring.
I have the following structure.
//Livro.Java
@Entity
public class Livro {
@JsonInclude(Include.NON_NULL)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message = "Campo nome é obrigatorio")
private String nome;
@JsonInclude(Include.NON_NULL)
@JsonFormat(pattern = "dd/mm/yyy")
@NotNull(message = "Campo publicacao é obrigatorio")
private Date publicacao;
@JsonInclude(Include.NON_NULL)
private String editora;
@JsonInclude(Include.NON_NULL)
private String resumo;
@OneToMany( mappedBy = "livro", fetch = FetchType.LAZY )
private List<Comentario> comentarios;
//Comentario.Java
@Entity
public class Comentario {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonProperty("comentario")
private String texto;
private String usuario;
@JsonFormat(pattern = "dd/mm/yyy")
private Date data;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "LIVRO_ID")
@JsonIgnore
private Livro livro;
// Livrosrepository.java
package com.curso.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.curso.domain.Livro;
public interface LivrosRepository extends JpaRepository<Livro, Long> {
}
//Comentariosrepository.java
package com.curso.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.curso.domain.Comentario;
public interface ComentariosRepository extends JpaRepository<Comentario, Long> {
}
// Livrosservice.java
@Service
public class LivrosService {
@Autowired
private LivrosRepository livrosRepository;
@Autowired
private ComentariosRepository comentariosRepository;
// [...]
public List<Livro> listar() {
return livrosRepository.findAll();
}
}
When I make a Request to list the Books, the behavior I hope is that it lists all the book data, but without the comments, because I am using the annotation java
fetch = FetchType.LAZY
but the behavior I have is the return of all Book data.
[
{
"id": 4,
"nome": "Teste2",
"publicacao": "01/01/2018",
"editora": "Polenta",
"comentarios": [
{
"id": 1,
"usuario": "tester",
"data": "26/03/2019",
"comentario": "Comentario 1"
}
]
}
]