How do I setup a ManyToOne relationship using JPA with AppEngine?

百般思念 提交于 2019-12-12 09:55:02

问题


I've been trying to get a relationship working with 2 entities in AppEngine, using JPA, and am currently running into this error:

java.io.IOException: com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain

My entities look like this:

@Entity
public class MyUser {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key key;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
    private List<MyMessage> messages;
}

and this:

@Entity
public class MyMessage {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key key;

    @ManyToOne(optional=false)
    private MyUser user;

}

The user already exists, and here is where I'm inserting a new message and get the recursion error:

EntityManager mgr = getEntityManager();
MyUser myuser = mgr.find(MyUser.class, KeyFactory.createKey("MyUser", user.getEmail()));
mymessage.setUser(myuser);
myuser.addMessage(mymessage);
mgr.persist(myuser);
mgr.persist(mymessage);

How am I supposed to setup this relationship within JPA and AppEngine guidelines? Thank you!

UPDATE

My problem was involving Jackson, not JPA. The JPA relationship is fine, but I needed to remove the relationship and manage it through the code as it was causing infinite recursion in serializing messages referring to users referring to messages and so on. I've also had to make sure that I annotated the user property in MyMessage as @Transient to avoid persistence complaining about persisting a parent owned by a child which already existed.


回答1:


I'm unaware of a reasonable way for Endpoints to serialize these classes. The JSON resulting from your current code would look smiilar to the following:

// 1
{
  "key": "foo",
  "messages": [
    {
      "key": "bar",
      "user": {
        // repeat 1
    },
  // and so on...
}

Your best bet is to define a class (or classes) to send over the wire, instead of your JPA entities, which define JSON an infinite number of levels deep.




回答2:


Obviously your message is nothing to do with JPA persistence, it's to do with Jackson (so presumably related to how you pass those objects back?). Only you know where that is invoked from. Whether your actual persistence operation succeeds or not is not clear from your post since you don't produce the stack trace, and rest of persistence code (like where that Jackson call originates)



来源:https://stackoverflow.com/questions/15032728/how-do-i-setup-a-manytoone-relationship-using-jpa-with-appengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!