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();