0

Every time I write a 'create' method in a DAO I have to construct the objects with the annotation @ManyToOne when they already exist and I only have the id. Like in the following example.

I have the class Employee:

@Entity  
public class Employee  
{  
    @Id
    private Long id;  

    private String employeeName;  

    @ManyToOne
    private Employer employer;  

    ...

}

And in the DAO I have a method to create an employee using the id of an already existing Employer. This is how I usually solve it:

public class EmployeeDAO {

    ...


    public void createEmployee(String name, String employerId) {

        Employee employee = new Employee();
        employee.setName(name);

        Employer employer = new Employer();
        employer.setId(employerId);
        employee.setEmployer(employer);

        save(employee);
    }

    ...
}

I would like to know if there is a more elegant way of doing this without making the 'new Employer()'

JorgeBPrado
  • 195
  • 1
  • 3
  • 14

1 Answers1

3

With your code, you can get a NonUniqueObjectException if your employer is already loaded in persistence context.

The best way to do it is to load a proxy of the employer. You can do it by using :

// for hibernate session
Employer employer = session.load(Employer.class, employerId);

// EntityManager
Employer employer = entityManager.getReference(Employer.class, employerId);

or use the JpaRepository#getOne method if you Spring Data.

you can read this question for more explanation.

victor gallet
  • 1,819
  • 17
  • 25
  • I dont get the exception as long as the Cascade is left as default (no cascade at all). – JorgeBPrado Nov 11 '15 at 21:16
  • I wanted to make it lighter, but if I have to even retrieve the parent it is going to cost even more... – JorgeBPrado Nov 11 '15 at 21:17
  • I seriously think this is a really good approach, if you already have the object reference (id), it's always good to retrieve it from database before setting on another entity and then save, especially using EntityManager's getReference which will not hit database if you already have the object loaded elsewhere. – Bonifacio Nov 11 '15 at 23:18