JPA persist object against ManyToOne

I have a @OneToMany company / employee @OneToMany in my database, which is defined as:

 @Entity public class Employee { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private long id; @ManyToOne @JoinColumn(name="companyid") Company company; .... } @Entity public class Company { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private long id; ... } 

Now I am adding a newly created employee to a separate company. The code I use looks something like this:

 Company company = em1.find(Company.class, 555L); em1.close(); EntityTransaction et = em2.getTransaction(); et.begin(); Employee employee = new Employee(); employee.company = company; em2.persist(employee); et.close(); 

Will this work fine?
Is hibernation about to merge the company into a second EntityManager or just use your id and save the employee object?
Can hibernation somehow duplicate my company object or throw an exception, saying that a company with the same identifier already exists in the database?

+6
java hibernate jpa entity-relationship
source share
1 answer
  • In the described case, the Company id will be used when saving the Employee object, but the Company itself will not be merged (note that Employee is the party that owns the relationship)
  • If the Company is transient rather than disconnected, you will receive the error message "object refers to an unsaved random instance"
  • If cascade = CascadeType.PERSIST , you will receive the error message โ€œDisabled object passed for savingโ€.

From the JPA specification:

If X is a managed entity, it is synchronized with the database.

  • For all objects Y referenced by relations from X, if the relation to Y was annotated with the value of the cascade element cascade = PERSIST or cascade = ALL, the save operation is applied to Y.
  • For any object Y referenced by a relation from X, where the relation to Y was not annotated by the cascading element value cascade = PERSIST or cascade = ALL:
    • If Y is new or deleted, an IllegalStateException is thrown by a flash operation (and the transaction marked for rollback) or the commit of the transaction will fail.
    • If Y separates, the semantics depend on the ownership of the relationship. If X owns the relationship, any changes to the relationship are synchronized with the database; if Y belongs to the relationship, the behavior is undefined.
+8
source share

All Articles