I have a scenario where a user after getting saved in the table, a role has to be created, the role table has a foreign key reference which is userId.
I tried writing some code when I debug I could see the method getting called, but the query isn't executing. Following is my code,
Handler
Mono<User> userResponse = service.create(user);
return ServerResponse.status(HttpStatus.CREATED).body(userResponse, User.class).switchIfEmpty(ServerResponse.badRequest().build());
Service
Mono<User> user = this.repository
.create(User.builder().userName(user.getUserName()).build())
.convert().with(toMono());
return user.map(u -> {
this.saveRoleForUser(u);
return u;
});
public void saveRoleForUser(User u) {
this.repository.getRole("roleName").flatMap(i -> {
return this.repository.createRole(Roles.of(null, u.userId, i.getRoleId));
});
}
I could see the getRole("roleName") is getting called in the repository, but the query isn't executing.
There's no error in the repository, I guess it's because of the thread blocking that's not allowing this query to execute. I tried searching for the solution but using flatMap should solve the problem is what I got to know. I even tried calling "saveRoleForUser" from the handler class, that isn't working too.
Repository
public Uni<Role> getRole(String roleName) {
CriteriaBuilder cb = this.sessionFactory.getCriteriaBuilder();
CriteriaQuery<Role> query = cb.createQuery(Role.class);
Root<Role> root = query.from(Role.class);
query.where(cb.equal(root.get("roleName"), roleName));
return this.sessionFactory.withSession(session -> session.createQuery(query).getSingleResultOrNull()).onItem()
.ifNull().switchTo(Uni.createFrom().item(Role.builder().build()));
}
PS: The user is getting created, I'm not getting any errors or exceptions.
Any help is much appreciated.
Thanks in advance.
CodePudding user response:
Here's is some sample code of ideally what the code should look like.
The most important thing to note here, is that we will now be subscribing to the Mono
returned from saveRoleForUser
which ensures the operations inside that function will get executed after the subscription occurs.
public Mono<User> createUser() {
return this.repository
.create(User.builder().userName(user.getUserName()).build())
.convert().with(toMono())
.flatMap(u -> this.saveRoleForUser(u));
}
public Mono<User> saveRoleForUser(User u) {
this.repository.getRole("roleName").flatMap(i -> {
return this.repository.createRole(Roles.of(null, u.userId, i.getRoleId));
}).thenReturn(u);
}