1

I work on a spring boot, data jpa web application and have a problem with an entity that has a @transient field and I want to bind result of my native query to this entity (all fields even @transient field)

suppose Chat entity class in brief :

    @entity
public class Chat  implements  Serializable{

@Id
@GeneratedValue(strategy =  GenerationType.IDENTITY)
private long id;

@ManyToOne
@JoinColumn(name="user_from")
private User userFrom;

@ManyToOne
@JoinColumn(name="user_to")
private User userTo;

@Transient
private int unread;

//getter and setter }

I have a native query that get chat list of user by left joining of chat table with chat_message table, in my select statement I have something like this:

select c.*,count(m.id) as unread from chat c left join chat_message m where ...

I need to bind result of this query to my chat entity, and it is important to value of unread field of above query set to my @transient unread field of chat class,

but this @transient field ignored by data jpa I tried more and more by using @SqlResultSetMapping and data jpa projection and ..., but there was no result for me. by using @SqlResultSetMapping, @transient filed still ignored, by using jpa projection, @transient filed is ok, but UserFrom and UserTo fields are null.

please guide me to overcome this problem if you had a similar experience or have any idea about this,

thanks

6
  • That's not possible. Transient fields are ignored by JPA Commented Jul 6, 2022 at 12:31
  • @SimonMartinelli thanks for your response, oh...what should I do in this situation? how to get unread from my native query and map to my entity? select c.*,count(m.id) as unread from chat c left join chat_message m where.... Commented Jul 6, 2022 at 14:27
  • You can do it yourself with a JPQL query similar to "Select c, size(c.messages) from Chat c where ...". Assuming you have a OneToMany to chat_messages mapped as messages, this will return Chat instances with the count(m.id) value - you then have to loop through the returned list and set the transient with the count, or just use the value and keep your Entity as is. Alternatively, you can map it as a DTO smarterco.de/spring-data-jpa-query-result-to-dto Commented Jul 6, 2022 at 14:44
  • You shouldn't map it to an Entity but a DTO Commented Jul 6, 2022 at 15:27
  • @Chris thanks, when map the result as a DTO, how to manage fileds of DTO that related to manyToOne fileds of entity ? I get null for userFrom and userTo of my DTO because there is no manyToOne annotation in DTO. can you explain me how to create query and DTO for my scenario? Commented Jul 12, 2022 at 7:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.