[Draft] Using Blaze Persistence - vinhtbkit/bkit-kb GitHub Wiki
<dependency>
<groupId>com.blazebit</groupId>
<artifactId>blaze-persistence-integration-hibernate-6.2</artifactId>
<version>${blaze-persistence.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.blazebit</groupId>
<artifactId>blaze-persistence-integration-spring-data-3.1</artifactId>
<version>${blaze-persistence.version}</version>
<scope>compile</scope>
</dependency>
Given the following Database relationship
---
title: Customer - Orders
---
erDiagram
USER ||--o{ POST : has
USER {
string email
string id PK
}
POST {
string id PK
string name
}
- The customer has one-to-many relationship to orders
@Entity
public class UserEntity {
@Id
private String id;
private String email;
@OneToMany(mappedBy = "user")
private Set<PostEntity> posts;
}
@Entity
public class PostEntity {
@Id
private String id;
private String title;
@ManyToOne(fetch = FetchType.LAZY)
private UserEntity user;
}
-
EntityView
: read-only projections of entity
@EntityView(UserEntity.class)
public interface UserEntityView {
@IdMapping
String getId();
String getEmail();
Set<PostEntityView> getPosts();
}
@EntityView(PostEntity.class)
public interface PostEntityView {
@IdMapping
String getId();
String getTitle();
}
First, need to enable it:
@EnableEntityViews
public class BlazeCteApplication {
// more code
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@Lazy(false)
// inject the criteria builder factory which will be used along with the entity view manager
public EntityViewManager createEntityViewManager(CriteriaBuilderFactory cbf, EntityViewConfiguration entityViewConfiguration) {
return entityViewConfiguration.createEntityViewManager(cbf);
}
}
Query:
private final EntityViewManager evm;
public Page<UserEntityView> findAll(String email, Pageable pageable) {
var res = evm.applySetting(EntityViewSetting.create(UserEntityView.class), cbf.create(em, UserEntity.class))
.orderByAsc("id") // Blaze requires at least one sort by "id" field
.pageBy(pageable.getPageNumber(), pageable.getPageSize(), "id") // "id" is used for grouping results
.getResultList();
return new PageImpl<>(res, pageable, res.size());
}
The actual query looks like this
select
u1_0.id,
u1_0.email,
p1_0.id,
p1_0.title,
(select
count(*)
from
usr u2_0)
from
usr u1_0
left join
post p1_0
on u1_0.id=p1_0.user_id
where
u1_0.id in(select
u3_0.id
from
usr u3_0
order by
u3_0.id fetch first 3 rows only)
order by
u1_0.id