java - JPA,保存关系而不查询实体

标签 java spring hibernate spring-data-jpa

我有这个实体代表两个其他实体之间的关系。

我想保存关系,而无需在保存之前获取角色和权限。

我想要像 .save(roleId,privilegeId) 这样的东西,这样我就不必在保存关系之前访问数据库。

这可能吗?如何实现?

谢谢

@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;
  }
}

这是该实体的 Spring Data JPA 存储库

@Repository
public interface RolePrivilegeRepository extends JpaRepository<RolePrivilege, RolePrivilegeId> {}

最佳答案

带有原始EntityManager您可以使用 em.getReference(Class<T> clazz, Object primaryKey)仅获取对您希望链接的实体的引用,而不实际获取该实体的数据。

关于java - JPA,保存关系而不查询实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45707509/

相关文章:

java - 使用 XSSFWorkbook 和 AbstractExcelView

java - 基于注解的工厂方法

java - Spring 的数据绑定(bind)器 autoGrowCollectionLimit 不能正常工作

java - Spring Boot with postgres --> HikariPool-1 - 池初始化期间出现异常

java.lang.RuntimeException : Camera. setParameters

java - RESTful 服务器上的 ISO 到 UTF-8

java - 支柱2 : Set ID of <td> to iterator value?

Android Groovy 网络服务

jquery - Hibernate 查询中的左连接

从 Windows 机器运行 shell 命令的 Java 程序