Jam*_*mes 5 java spring hibernate jpa spring-data-jpa
我有一个 Spring 数据存储库,我可以在其中获取一组帐户的所有位置:
public interface PositionRepository extends JpaRepository<Position, PositionKey> {
@EntityGraph(value = "Position.all", type = EntityGraphType.LOAD)
List<Position> findByAccountIn(Set<Account> accounts);
}
Run Code Online (Sandbox Code Playgroud)
Position具有也是实体的属性(一些嵌套级别):
@Entity
@NamedEntityGraph(name = "Position.all",
attributeNodes = {@NamedAttributeNode("account", subgraph = "Account.all"),
@NamedAttributeNode("product", subgraph = "Product.all")
})
@Data
public class Position {
@EmbeddedId
private PositionKey positionKey;
@MapsId("accountId")
@ManyToOne
@JoinColumn(name = "accountId")
private Account account;
@MapsId("productId")
@ManyToOne
@JoinColumn(name = "productId")
private Product product;
}
@Embeddable
@Data
public class PositionKey implements Serializable {
@Column(name = "accountId")
private Long accountId;
@Column(name = "productId")
private Long productId;
}
@Entity
@NamedEntityGraph(includeAllAttributes = true, name = "Product.all",
attributeNodes = {@NamedAttributeNode(value = "vendor", subgraph = "Vendor.all"),
@NamedAttributeNode(value = "type", subgraph = "ProductType.all")}
)
@Data
public class Product {
@Id
@Column(name = "id")
private Long id;
@ManyToOne
@JoinColumn(name = "typeId")
private ProductType type;
@ManyToOne
@JoinColumn(name = "vendorCode")
private Vendor vendor;
}
@Entity
@NamedEntityGraph(name = "Account.all")
@Data
public class Account {
@Id
@Column(name = "accountId")
private Long id;
}
Run Code Online (Sandbox Code Playgroud)
我总是将持仓的完整实体图作为序列化 JSON 返回给客户端。因此,我总是需要所有属性和嵌套属性。位置实例最多为 350 个。
尽管使用了@NamedEntityGraph,我注意到仍然发出个别查询。例如,我收到每个唯一供应商的查询。通常需要大约 2-3 秒才能获取所有单独查询的结果。
我如何告诉 JPA 发出具有多个联接的一个查询?我可以手动编写此 SQL(使用多个联接),并且它会在几毫秒内返回。
更新
数据访问方式如下:
@RestController
@RequestMapping("/position")
@RequiredArgsConstructor
public class PositionController {
private final PositionRepository positionRepo;
@GetMapping
public List<Position> getAllPositions(Set<Account> accounts) {
return positionRepo.findByAccountIn(account);
}
}
Run Code Online (Sandbox Code Playgroud)
返回职位列表后,它们将通过 Jackson 进行序列化。所以,真正访问数据的是杰克逊。
| 归档时间: |
|
| 查看次数: |
815 次 |
| 最近记录: |