Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the error report of JPA @ ManyToMany

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains how to solve the problem of JPA @ ManyToMany. Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "JPA @ ManyToMany how to solve the error report"!

JPA @ ManyToMany reported an error StackOverflowError

@ ManyToMany using SpringBoot + JPA encountered the following error

Java.lang.StackOverflowError: null

2021-02-07 10 o.a.c.c.C 59.490 ERROR 100440-[io-20012-exec-3] o.a.c.c.C. [dispatcherServlet]:

Servlet.service () for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed

Nested exception is org.springframework.http.converter.HttpMessageNotWritableException:

Could not write JSON: Infinite recursion (StackOverflowError)

Nested exception is com.fasterxml.jackson.databind.JsonMappingException:

Infinite recursion (StackOverflowError) (through reference chain:

Com.xxx.entity.boem.EquipmentManage ["dataPublishes"]-> org.hibernate.collection.internal.PersistentSet [0]

-> com.xxx.entity.bods.DataPublish ["equipmentManages"]-> org.hibernate.collection.internal.PersistentBag [0]

-> com.xxx.entity.boem.EquipmentManage ["dataPublishes"]-> org.hibernate.collection.internal.PersistentSet [0]

-> com.xxx.entity.bods.DataPublish ["equipmentManages"]-> org.hibernate.collection.internal.PersistentBag [0]

-> com.xxx.entity.boem.EquipmentManage ["dataPublishes"]-> org.hibernate.collection.internal.PersistentSet [0]

->.

.

Note:

When using @ ManyToMany, the corresponding Entity cannot use the @ Data annotation of lombok. Use @ Setter, @ Getter annotations. The main reason is to override the hash () equals (), toString () methods. In this way, there are no exceptions when adding and deleting. Otherwise, a circular reference appears and cannot be deleted or stackOver

Unable to delete and add successfully, the main problem with the loop is the toString () method. This method can only contain basic elements, not the corresponding @ ManyToMany object. Both classes. Only in this way can ok.

@ Setter@Getter@Entitypublic class User {@ Id @ GenericGenerator (name= "jpauuid", strategy = "org.hibernate.id.UUIDGenerator") @ GeneratedValue (generator = "jpauuid") @ Column (length = 32 length nullable = false) private String id; @ Column (length = 30) private String username; @ ManyToMany (cascade = CascadeType.REFRESH,mappedBy = "users") private Set roles; @ Override public boolean equals (Object o) {if (this = = o) return true If (o = = null | | getClass ()! = o.getClass ()) return false; User user = (User) o; return id.equals (user.id) & & username.equals (user.username) & & roles.equals (user.roles);} @ Override public int hashCode () {return Objects.hash (id, username, roles) } @ Override public String toString () {return "User {" + "id='" + id +'\'+ ", username='" + username +'\'+ ", roles=" + roles +'}';} @ Setter@Getter@Entitypublic class Role {@ Id @ GeneratedValue (strategy = GenerationType.AUTO) private Integer id @ Column (length = 30) private String name; @ ManyToMany (cascade = CascadeType.REFRESH) @ JoinTable (name= "user_role", joinColumns = @ JoinColumn (name= "role_id"), inverseJoinColumns = @ JoinColumn (name= "user_id") private Set users;} StackOverFlow caused by SpringJPA batch deletion

There is a code in the project that deletes some historical data in batches according to Id (xxxRepository.deleteInBatch (list);) and finds that stack overflow (StackOverFlowError) occurs when the incoming list is too large.

Solution method

List is divided into multiple parts and deleted in batches.

Here is a simple understanding of the execution process.

DeleteInBatch (Iterable entities) / * * tap into the source code to see. Org.springframework.data.jpa.repository.support.SimpleJpaRepository#deleteInBatch*/ @ Transactional public void deleteInBatch (Iterable entities) {Assert.notNull (entities, "The given Iterable of entities not be null!"); if (! entities.iterator (). HasNext ()) {return } / / continue tracking applyAndBind (getQueryString (DELETE_ALL_QUERY_STRING, entityInformation.getEntityName ()), entities, em) .executeUpdate ();} / * * org.springframework.data.jpa.repository.query.QueryUtils#applyAndBind*/ public static Query applyAndBind (String queryString, Iterable entities, EntityManager entityManager) {/ /. Omitting some code / / will result in delete from xx table x (table alias) where x.id =? Or X. idler... A sql statement String alias = detectAlias (queryString); StringBuilder builder = new StringBuilder (queryString); builder.append ("where"); int I = 0; while (iterator.hasNext ()) {iterator.next () Builder.append (String.format ("% s =? d", alias, + + I)); if (iterator.hasNext ()) {builder.append ("or");}} Query query = entityManager.createQuery (builder.toString ()) Iterator = entities.iterator (); I = 0; while (iterator.hasNext ()) {query.setParameter (+ + I, iterator.next ());}}

Combined with the logging error messages, go to the org.hibernate.hql.internal.antlr.HqlSqlBaseWalker#logicalExpr method

Paste the call stack below

The logicalExpr method is called by whereClause () in the org.hibernate.hql.internal.antlr.HqlSqlBaseWalker#deleteStatement method.

As you can see from the following figure, this method recursively calls itself at ①, and will constantly create stack frames. When the stack depth or stack size is exceeded, stack overflow will occur.

As for how to jump out of ① and continue to execute the following code, it has not been studied. If you have any knowledge, please advise me and correct your inaccuracies.

At this point, I believe you have a deeper understanding of "JPA @ ManyToMany error reporting how to solve", might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report