I am using JPA in my project.
I came to a query in which I need to make join operation on five tables. So I created a native query which returns five fields.
If you use Spring-jpa
, this is a supplement to the answers and this question. Please correct this if any flaws. I have mainly used three methods to achieve "mapping result Object[]
to a pojo" based on what practical need I meet:
sql
with its Entity
are enough.The former 2 failed, and I have to use a nativeQuery
.
Here are the examples.
The pojo expected:
public class Antistealingdto {
private String secretKey;
private Integer successRate;
// GETTERs AND SETTERs
public Antistealingdto(String secretKey, Integer successRate) {
this.secretKey = secretKey;
this.successRate = successRate;
}
}
Method 1: Change the pojo into an interface:
public interface Antistealingdto {
String getSecretKey();
Integer getSuccessRate();
}
And repository:
interface AntiStealingRepository extends CrudRepository {
Antistealingdto findById(Long id);
}
Method 2: Repository:
@Query("select new AntistealingDTO(secretKey, successRate) from Antistealing where ....")
Antistealing whatevernamehere(conditions);
Note: parameter sequence of POJO constructor must be identical in both POJO definition and sql.
Method 3:
Use @SqlResultSetMapping
and @NamedNativeQuery
in Entity
as the example in Edwin Dalorzo's answer.
The first two methods would call many in-the-middle handlers, like customized converters. For example, AntiStealing
defines a secretKey
, before it is persisted, a converter is inserted to encrypt it. This would result in the first 2 methods returning a converted back secretKey
which is not what I want. While the method 3 would overcome the converter, and returned secretKey
would be the same as it is stored (an encrypted one).