I performed a test with your mapping, and did not generate the reported problem.
Departmental class:
@Entity
@Data
public class Departamento {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message="O campo descrição é obrigatório")
private String descricao;
@JsonProperty(access = Access.WRITE_ONLY)
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name= "subordinador")
private List<Departamento> subordinados;
}
I created a repository to make a test query:
public interface DepartamentoRepository extends JpaRepository<Departamento, Long> {
}
I created a class to run on Spring Startup:
@Component
@Data
@AllArgsConstructor
public class Inicializacao {
DepartamentoRepository repository;
@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
this.salvarDepartamentos();
this.recuperarDepartamentos();
}
public void salvarDepartamentos() {
Departamento fiscal = new Departamento();
fiscal.setDescricao("fiscal");
repository.save(fiscal);
Departamento almoxarifado = new Departamento();
almoxarifado.setDescricao("almoxarifado");
repository.save(almoxarifado);
Departamento administracao = new Departamento();
administracao.setDescricao("administracao");
administracao.setSubordinados(Arrays.asList(fiscal, almoxarifado));
repository.save(administracao);
}
public void recuperarDepartamentos() {
Optional<Departamento> retorno = repository.findById(3L);
Departamento departamento = retorno.get();
System.out.println(departamento.getSubordinados());
}
}
The call in the code department.getSubordinated() generates exactly the expected error of Lazy:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.demo.model.Departamento.subordinados, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:606) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
AbstractPersistentCollection.java:606
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
AbstractPersistentCollection.java:218
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:585) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
AbstractPersistentCollection.java:585
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
AbstractPersistentCollection.java:149
at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:621) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
PersistentBag.java:621
at java.base/java.lang.String.valueOf(String.java:3388) ~[na:na]
String.java:3388
at java.base/java.io.PrintStream.println(PrintStream.java:1047) ~[na:na]
PrintStream.java:1047
at com.example.demo.model.Inicializacao.recuperarDepartamentos(Inicializacao.java:46) ~[classes/:na]
Inicializacao.java:46
That is, the data is not being loaded, because by default Onetomany = LAZY. In its mapping was still explicit.
The specification contained in JSR-000317 informs that by default:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
Only one select was generated in the log (also expected):
2021-05-19 08:57:07.287 INFO 43976 --- [ restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged
Hibernate: select departamen0_.id as id1_0_0_, departamen0_.descricao as descrica2_0_0_ from departamento departamen0_ where departamen0_.id=?
Pom used in demo project:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>