假設我的應用程式中有以下物體:
@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 ,但我只想部分加載 anotherEntities ,例如我只想要它的最后 10 個版本,最簡單和最直接的方法是什么(使用 Hibernate /Spring Data JPA) 一個請求?
問題2:
我想更新前面提到的物件并向串列中添加一個新的 AnotherEntity,但是 JpaRepository 的 save(T t) 方法保存了整個物件,而我丟失了未加載的物件。如何保存物件,以便 Spring Data(樂觀鎖定)更新版本并且 SomeEntity 不會丟失以前的資料?
更新1:
我正在使用 Postgresql 作為資料庫。
uj5u.com熱心網友回復:
根據您的確切限制,您有不同的選擇。
您可以使用@Where注釋:
@Data
@Entity
public class SomeEntity {
@Id
private Long id;
@OneToMany
@Where(clause = "version < 10")
private List<AnotherEntity> anotherEntities = new ArrayList<>();
@Version
private Long version;
}
您可以使用過濾器:
@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();
您可以將關聯映射為雙向(或多對一)
@Data
@Entity
public class SomeEntity {
@Id
private Long id;
@OneToMany(mappedBy = "someEntity")
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;
@ManyToOne
private SomeEntity someEntity;
}
現在您可以使用 HQL 查詢獲取物體串列:
from AnotherEntity ae where ae.someEntity.id = 1 and ae.version < 10
當您想創建一個新的AnotherEntity時,您可以SomeEntity從結果串列中的任何元素中獲取,或者您可以使用EntityManager#getReference(并避免運行查詢):
AnotherEntity ae = new AnotherEntity(...);
ae.setSomeEntity(em.getReference(SomeEntity.class, 1));
em.persist(ae);
該關聯是惰性的,因此 Hibernate 不會加載整個集合(除非您需要訪問它)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/521161.html
