Issue
I have this Entity representing a relation between two other entities.
I'd like to save the relation without having to get Role and Privilege before saving.
I'd like something like .save(roleId, privilegeId) so I don't have to hit the database before saving the relation.
Is it possible and how ?
Thanks
@Entity
@Table(name = "security_role_privilege")
public class RolePrivilege implements Serializable {
private static final long serialVersionUID = -4788066966268187121L;
@EmbeddedId protected RolePrivilegeId id;
@ManyToOne
@JoinColumn(name = "role_id", insertable = false, updatable = false)
protected Role role;
@ManyToOne
@JoinColumn(name = "privilege_id", insertable = false, updatable = false)
protected Privilege privilege;
protected RolePrivilege() {}
public RolePrivilege(Role role, Privilege privilege) {
super();
this.role = role;
this.privilege = privilege;
this.id = new RolePrivilegeId(role.getId(), privilege.getId());
this.privilege.getRolePrivileges().add(this);
this.role.getRolePrivileges().add(this);
}
public RolePrivilegeId getId() {
return this.id;
}
public Role getRole() {
return this.role;
}
public Privilege getPrivilege() {
return this.privilege;
}
}
This is the Spring Data JPA Repository for this entity
@Repository
public interface RolePrivilegeRepository extends JpaRepository<RolePrivilege, RolePrivilegeId> {}
Solution
With a raw EntityManager
you can use em.getReference(Class<T> clazz, Object primaryKey)
to fetch only a reference to the entity you wish to link, without actually fetching the data for the entity.
Answered By - Kayaman