I am having problems with Hibernate when fetching a list of objects with a ManyToOne relation. Below you can find the Entity and the Repository file. You can see that the Portofolio object has a benchmark which is a Portfolio itself.
The Entity
@Entity
//@NamedEntityGraph(name = "Portfolio.benchmark", attributeNodes = @NamedAttributeNode("benchmark"))
@Table(name = "PORTFOLIOS")
public class Portfolio {
...
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BENCHMARK_ID", insertable = false, updatable = false)
private Portfolio benchmark;
@Column(name = "BENCHMARK_ID")
private Long benchmarkId;
....
}
The Repository
@Repository
public interface PortfolioRepository extends CrudRepository<Portfolio, Long> {
//@EntityGraph(value = "Portfolio.benchmark", type = EntityGraph.EntityGraphType.LOAD)
//@Query("select portfolio from Portfolio portfolio left join fetch portfolio.benchmark where upper(portfolio.userName) = upper(:userName) ")
List<Portfolio> findAllByUserNameIgnoreCase(String userName);
}
The commented code are approaches that I tried before but did not work.
The Scenario
I have 3 portfolios with the following ids; let's say: 1, 2, 3
Portfolio 1 has as benchmark the Portfolio id 2 and portfolio 2 has as benchmark the Portfolio id 3.
When executing the repository method findAllByUserNameIgnoreCase
, I need to have a list of portfolios for that user, with the information of each benchmark.
The information for the Portfolio 1 is loaded properly, but for the porfolio 2, the benchmark is not loaded.
Here is a representation of the response:
(Portfolio@20661) = {portfolioId=1, benchmarkId=2, benchmark@20680 = {portfolioId=2, benchmarkId=3, benchmark = null}}
(Portfolio@20680) = Portfolio{portfolioId=2, benchmarkId=3, benchmark = null}
(Portfolio@20698) = Portfolio{portfolioId=3, benchmarkId=null, benchmark = null}
As we can see the porfolio 2 has the Java object reference 20680. It is the same in the benchmark attribute of the portfolio 1, and it is correct.
I don't understand, why for the Portfolio 1, the benchmark relation was fetched, for the Portfolio 2, the benchmark was not.
I tried to configure EntityGraph but it did not have any effect.
What am I doing wrong? How can I get all the benchmark references resolved when calling the findAll
method?
I found the problem, and tipically it is between the screen and the chair.
The problem was not in the entity nor the repository. It was a mapper to DTO that was setting in propertly a relation to null.
I am sorry about this, and thank you so much for the attention you gave to my question.
Cheers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.