2

I'm using the JPA implementation EclipseLink and a MySQL server for the persistence layer of my application. My problem is, that an object which was already persisted and already have an id, is getting inserted a second time through a many-to-one relationship withe CascadeType.All.

Here the entities:

@Entity
@Table(name = "messages")
public class Message extends DbObject {

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    public User author;

    public String message = "";

    public Timestamp timestamp;

       // Getters and setters removed ....
}


@Entity
@Table(name = "users")
public class User extends DbObject {

    private String name;

    // Getters and setters removed ....
}


@MappedSuperclass
public abstract class DbObject {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
}

When I run the following code, then I have two entries in my "users" table. But I just want to assign the already existing user to a Message Object and not to create a new User.

User user = getCurrentUser(); // The user object is already persistent  

Message msg = new Message();
msg.setUser(user);
EntityManager em = createEntityManager();
em.getTransaction().begin();
em.persist(msg);
em.getTransaction().commit();
em.close();
user1879086
  • 53
  • 1
  • 5

1 Answers1

2

The user is detached from the entityManager you are using to persist the Message, and with cascade persist set on the relationship to user, JPA requires that persist also occur on your detached User. Options are to A) read it using the current persistence so it is managed. Persist is a no-op on managed entities other than to cascade. B) remove the cascade all on the Message->user relationship C) use merge instead of persist for the message instance. Merge will still persist it, but will correctly copy User state into a managed user instance.

Chris
  • 20,138
  • 2
  • 29
  • 43