2

I use spring boot 3. I try to create a native query with entity manager, i would like to feed a dto

@SqlResultSetMapping(
        name = "BookResultMapping",
        classes = @ConstructorResult(
                targetClass = BookSearchResult.class,
                columns = {
                        @ColumnResult(name = "code"),
                        @ColumnResult(name = "title")}))
public class BookSearchService {

    @PersistenceContext
    private EntityManager entityManager;

    public void bookSearch(Search search){
         StringBuilder sbSqlQuery = new StringBuilder();
         ...
         Query query = entityManager.createNativeQuery(sbSqlQuery.toString(), "BookResultMapping");
         ...
    }
}


@Data
@RequiredArgsConstructor
public class BookSearchResult {

    private String code;
    private String title;
}

When i run this code, I get

Could not resolve specified result-set mapping name : BookResultMapping

Edit, I tried to but code related to SqlResultSetMapping directly to the dto, but i get same result

robert trudel
  • 5,283
  • 17
  • 72
  • 124
  • In this case Lombok creates only a no-arg default constructor. If you need to use Lombok, then use `@AllArgsConstructor` annotation. I strongly recommend do not use Lombok on entities and DTO-s. – zforgo Jun 12 '23 at 21:45
  • @zforgo, that don't fix the issue, BookResultMapping is not found – robert trudel Jun 12 '23 at 23:31

1 Answers1

1

Check this other answer: https://stackoverflow.com/a/36109273

In short, the @SqlResultSetMapping annotation should go in one of your @Entity classes in order to be detected. I think this is poorly documented and online examples always show the isolated annotation without much context.

If you wanted to avoid using any entity, you can so something like:

@SqlResultSetMapping(
        name = "MessageDTO",
        classes = @ConstructorResult(targetClass = MessageDTO.class, columns = {
                @ColumnResult(name = "message_body", type = String.class),
                @ColumnResult(name = "created_date", type = OffsetDateTime.class)
        })
)
@Embeddable
public static class SQLMappingConfigEntity {
    /* this dummy Embeddable class allows SqlResultSetMapping annotation to be picked up */
}

In this example, MessageDTO would be your DTO. It must have with a constructor will all arguments.