【问题标题】:Is there a way to retrieve an entity with list property but load the list with the last few entities?有没有办法检索具有列表属性的实体但使用最后几个实体加载列表?
【发布时间】:2022-10-23 23:55:58
【问题描述】:

假设我的应用程序中有以下实体:

@Data
@Entity
public class SomeEntity {
    @Id
    private Long id;

    @OneToMany
    private List<AnotherEntity> anotherEntities = new ArrayList<>();
    
    @Version
    private Long version;

}

@Data
@Entity
public class AnotherEntity {
    @Id
    private Long id;

    @Column
    private String someField;
    
    @Column
    private Long version;
  
}

问题一:

例如,我想加载一个 id = 1 的 SomeEntity ,但我只想部分加载另一个实体,例如我只想要它的最后 10 个版本,最简单和最直接的方法是什么(使用 Hibernate /Spring Data JPA) 一个请求?

问题2:

我想更新前面提到的对象并将新的 AnotherEntity 添加到列表中,但是 JpaRepository 的 save(T t) 方法保存了整个对象,而我丢失了未加载的对象。如何保存对象,以便 Spring Data(乐观锁定)更新版本并且 SomeEntity 不会丢失以前的数据?


更新 1:

我正在使用 Postgresql 作为数据库。

【问题讨论】:

  • 我不认为这是可能的。如果可能的话,合并实体可能会删除尚未加载的条目。如果您需要对数据进行这种精细控制,您可能不想映射 *tomany 关系并手动管理它。

标签: java hibernate jpa spring-data-jpa spring-data


【解决方案1】:

You can use the @Where annotation:

@Data
@Entity
public class SomeEntity {
    @Id
    private Long id;

    @OneToMany
    @Where(clause = "version < 10")
    private List<AnotherEntity> anotherEntities = new ArrayList<>();
    
    @Version
    private Long version;

}

或者,如果您想更好地控制何时应用条件,you can use a filter

@Data
@Entity
public class SomeEntity {
    @Id
    private Long id;

    @OneToMany
    @Filter(
        name="latestVersions",
        condition="version < :version"
   )
   private List<AnotherEntity> anotherEntities = new ArrayList<>();
   
}

您可以在使用会话运行查询之前启用过滤器:

entityManager
    .unwrap(Session.class)
    .enableFilter("latestVersions")
    .setParameter("version", 10);

List<Account> accounts = entityManager.createQuery(
    "from SomeEntity se where se.id = 1", SomeEntity.class)
.getResultList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多