Konrad
Konrad

Reputation: 1635

JPA relationship using id and object instance

I have a following JPA entities:

@Entity
class User {
  Long id;

  String name;

  // other fields
}

@Entity
class Department {
  @Id
  Long id;

  String name;

  // other fields
}

Now I would like to create relationship between user and department. When new user is created I don't want to fetch Department and set it using:

user.setDepartment(department);

Instead I prefer to just set the department id:

user.setDepartmentId(departmentId);

and leave it for database to validate foreign key constraint.

However, at the same time it should be possible to get full department data together with user. For example I would like to execute the following spring-data query:

SELECT u FROM UserModel as u LEFT OUTER JOIN FETCH u.department;

Is it possible to be achieved using:

Upvotes: 1

Views: 2714

Answers (1)

vbezhenar
vbezhenar

Reputation: 12356

You can use the following code:

Department department = entityManager.getReference(Department.class, departmentId);
user.setDepartment(department);

getReference won't issue select and will assume that this departmentId exists.

Upvotes: 4

Related Questions