79812539

Date: 2025-11-07 16:06:07
Score: 2
Natty:
Report link

Thank you everyone who helped. This is how I solved it.

<br>

**First, "LazyInitializationException":**

\> Method threw 'org.hibernate.LazyInitializationException' exception. Cannot evaluate com.dpr.berry.domain.entities.UserEntity.toString()

The problem here wasn't leaving the `FetchType` on the "OneToMany" part of the relationship as "LAZY", since that's the default anyway.

What was causing this problem was the Lombok `@Data` annotation. It wasn't behaving correctly when handling the variables that referenced the related entities.

The solution to this was writing my own `toString` for each entity, where i only included the ID + Name. Also, I got rid of the `@Data` annotations and instead I'm just using the `@Getter` and `@Setter` annotations.

<br>

**Second, "StackOverflowError":**

This problem happened when I set the `FetchType` on the "OneToMany" relationship as "EAGER".

The solution to this was leaving it as default, which is "LAZY", on the two sides of the "OneToMany" relationship. And also, setting it as "LAZY" on the "ManyToOne" part of the relationship, since the default there is "EAGER":

UserEntity:

```java

@OneToMany(mappedBy = "user")

@OnDelete(action = OnDeleteAction.CASCADE)

private Set<BerryInventoryEntity> berryInventory;

```

BerryEntity:

```java

@OneToMany(mappedBy = "berry")

@OnDelete(action = OnDeleteAction.CASCADE)

private Set<BerryInventoryEntity> berryInventory;

```

BerryInventoryEntity:

```java

@ManyToOne (optional = false, fetch = FetchType.LAZY)

@JoinColumn (name = "user_id")

private UserEntity user;

@ManyToOne (optional = false, fetch = FetchType.LAZY)

@JoinColumn (name = "berry_id")

private BerryEntity berry;

```

<br>

Also, i added `LEFT JOIN FETCH b.berry` to the `findInventoryOfUser` method on `BerryInventoryRepository`:

```java

@Query("SELECT b FROM BerryInventoryEntity b LEFT JOIN FETCH b.berry WHERE b.user = :user")

Iterable<BerryInventoryEntity> findInventoryOfUser(UserEntity user);

```

So this way I only fetch the data i need.

Reasons:
  • Blacklisted phrase (0.5): Thank you
  • Blacklisted phrase (0.5): i need
  • Blacklisted phrase (1): StackOverflow
  • Whitelisted phrase (-2): I solved
  • Long answer (-1):
  • No code block (0.5):
  • User mentioned (1): @ManyToOne
  • User mentioned (0): @JoinColumn
  • User mentioned (0): @ManyToOne
  • User mentioned (0): @JoinColumn
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Rikelo