I am getting a surprising output in my GET API built in springboot, I have two related entities, say A and B. Here A has @OneToOne mapping with B.
@Entity
class A {
....
@OneToOne
@JoinColumn(name = "b_id")
B b;
}
@Entity
class B {
Integer id;
....
}
And I am using the JpaRepository for entity A to find the requested entities in specified order.
public interface ARepo extends JpaRepository<A,Integer>, JpaSpecificationExecutor<A> {
...
}
and I am building a Pageable like this:
Pageable pageable = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "bId")); // bId i have specified for sorting
So when i execute the findAll() method of JPA i am getting outout in DESC order of b.id. It is so surprising and does my work but I want to know how is it working internally?
I checked for 'nested property path traversal' in hibernate but couldn't find anything about it.
I have a DTO class and a mapper for the same, I doubt that maybe its because this:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@FieldDefaults(level = AccessLevel.PRIVATE)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ADto {
Integer aId;
....
Integer bId;
}
@Mapper(componentModel = "spring", nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface AMapper {
@Mapping(target = "bId", source = "b.id")
ADto entityToDto(A refundInitiate);
}
The Sort.by(Sort.Direction.DESC, "bId")
method uses the expression bId
. Spring Data JPA interprets it as a CamelCase path consisting of the b
field in the object of class A
and the id
field of the object that b
points to, which is the object of class B
.
For more information, see the Spring Data JPA documentation.