zbender
zbender

Reputation: 387

JPA. Cast the field of @Entity in sql select

I have jpa entity:

@Entity
@Table(name = "document")
public class Document
...
@Column
private String docNumber;
...

And used JpaSpecificationExecutor to get result from DB:

Page<Document> findAll(@Nullable Specification<Document> spec, Pageable pageable)

In this case, spring-data-jpa make select like this:

select document0_."doc_number" from document

Can I tune jpa entity for select column with cast to int (perfectly, to other entity field):

select cast(document0_."doc_number" as int4) from document

It's needed, because in one case from many I get sql-query where select distinct used with order by cast(document0_."doc_number" as int4) and PostgreSQL return ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list.

Upvotes: 0

Views: 1991

Answers (1)

user10871691
user10871691

Reputation:

Since spring-data-jpa uses Hibernate as JPA engine, you can use Hibernate's @Formula annotation:

@Formula("cast('doc_number' as int4)")
private int docNumberAsInt4;

I haven't test it though.

Upvotes: 2

Related Questions