【问题标题】:How to define only selected foreign attributes in spring entity如何在spring实体中仅定义选定的外部属性
【发布时间】:2021-10-05 07:15:31
【问题描述】:

假设我有两个实体加入如下:

@Entity
public class User {
    @Id
    private Long id;
    private String username;
    private String password;

    @ManyToOne
    @JoinColumn(name="role_id", referencedColumnName = "id") //Table user in database has foreign key role_id
    private Role role;

}

@Entity
public class Role {
    @Id
    private Long id;
    private String name;
}

如何仅创建仅具有一个角色属性而不是整个属性的用户实体? (例如,仅角色名称)

我期待类似的东西

@Entity
public class User {
    @Id
    private Long id;
    private String username;
    private String password;

    // Some prefix or annotation maybe?
    private String role_name;

}

【问题讨论】:

  • 你不能。如果您的角色名称是唯一的,那么您可以将其用作 PK 并将其映射到 User 实体中。不属于User 表(或某些联结表)的任何其他字段都不能映射到User 表中。
  • 即使使用@Query 或某种视图 (SQL) 方法?
  • 好吧,你可以使用DTO projections。这样您就可以拥有一个包含您喜欢的任何字段的对象,但您将无法像在 @Entity 上那样进行任何操作。
  • 我已经阅读了一些 DTO 方法。虽然它可以解决问题,但我想它会出现 N+1 问题
  • 不,不会。您只有 1 个查询,并将结果映射到 DTO。您没有迭代延迟加载的 *ToMany 关系。

标签: java spring spring-boot hibernate


【解决方案1】:

就像您已经在 cmets 中读到的那样,您将需要一种 DTO 方法,我认为这是 Blaze-Persistence Entity Views 的完美用例。

我创建了该库以允许在 JPA 模型和自定义接口或抽象类定义模型之间轻松映射,例如 Spring Data Projections on steroids。这个想法是您按照自己喜欢的方式定义目标结构(域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

使用 Blaze-Persistence Entity-Views 的用例的 DTO 模型可能如下所示:

@EntityView(User.class)
public interface UserDto {
    @IdMapping
    Long getId();
    String getUsername();
    String getPassword();
    @Mapping("role.name")
    String getRoleName();
}

查询是将实体视图应用于查询的问题,最简单的就是通过 id 进行查询。

UserDto a = entityViewManager.find(entityManager, UserDto.class, id);

Spring Data 集成让您可以像使用 Spring Data Projections 一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

Page<UserDto> findAll(Pageable pageable);

最好的部分是,它只会获取实际需要的状态!

【讨论】:

    猜你喜欢
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    相关资源
    最近更新 更多