Skip to content
Advertisement

spring-data-jpa many to many findByID

i have many to many relationship between book and author, i have 3 tables: author, book and author_book.

JavaScript

i can add data to db without a problem, but when i want to get an author or a book by its id

JavaScript

i get an error: LazyInitialization failed to lazily …

I want to use FetchType.LAZY and get the instance of author or book.

Thank you for your time.

Advertisement

Answer

So, read the fine manual: 6.3.10. Configuring Fetch- and LoadGraphs.

Your issue is simply that your toString() methods are recursive. Authors says to print Books, and Books says to print Authors. Pro tip: success is in the details.

For a load or fetch you need to use an EntityGraph from JPA to specify the joined attributes. So:

JavaScript

and

JavaScript

With repositories:

JavaScript

and

JavaScript

Then you must print what you want yourself. Basically, putting toStrings in Entities generally causes problems, but you should also RTFM.

JavaScript

Finally, I avoid using Cascade annotations like the plague. They are complicated annotations. Also, ManyToMany is FetchType.LAZY by default. The important annotation is the mappedBy annotation. This tells you which entity owns the relationship. The owning entity is the one responsible for persisting relations. The other side of bidirectional annotations are really only for queries. There is no need to make new ArrayList in the entities since they will be thrown away anyway during queries. Just create a list when you need to persist a new Author entity with relations, otherwise use the lists returned by the queries.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement