merveotesi
merveotesi

Reputation: 2183

Cascade types: ALL, MERGE, etc

I have a person object, and a computer object, this person object has a field named computer, one person can have one computer, one-to-one relation.

class Person{

    @OneToOne(cascade=CascadeType.ALL)//in which situations this is true?  
    @JoinColumn(name = "computer_id",nullable=false) 
    private Computer computer;

    getComputer(){...}
    setComputer(Computer c){...}

    @Id
    private String id;
}

class Computer{

    @Id
    private String id;

}

Let me assume I have a computer object on DB, and I get it with a load method.

Computer computer=entityManager.loadById({an id});
Person p=new Person();
p.setComputer(computer);

Now if I want to save both of computer and person what should I do?

entityManager.persist(p);

I can not generate same error but a while ago I got a "detached entity passed to persist" error.

what is the most appropriate way to save everything into DB without repeatings?

Also can you advise a resource (a book maybe) to understand what to do in different situations.

Upvotes: 0

Views: 936

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

You don't need any cascade in the case you describe, and persisting the user is sufficient:

  • since the computer has been loaded using the EM, it's attached to the EM. Any change done on the computer will be automatically saved to the database without any operation needed
  • the user is a new entity, which is not persistent yet. To make it persistent, you must call persist. After this call, it will be attached to the EM, and any change done on the user will also be automatically saved to the database without any operation needed

The error "detached entity passed to persist" could happen if you created a new computer, then a new user, set the computer to the user, and persist the user. In this case, the EM complaions because you try to make persistent en entity (user) which refers to another entity (computer) which is not persistent. There are two solutions:

  • make the computer persistent before making the user persistent, by calling persist with the computer
  • annotate the person.computer association with cascade=PERSIST or cascade=ALL, so that the computer is made persistent autoamatically when the user is made persistent. Note that ALL also includes REMOVE. So if you remove a user, its computer will also be removed.

Upvotes: 3

Related Questions