添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
严肃的机器人  ·  合肥s - 图片搜索·  1 年前    · 
天涯  ·  小红书 - 标记我的生活·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am getting the following stacktrace:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [referencedata.ABDeadlineType] to type [referencedata.DeadlineType]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:324)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:206)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:187)
    at org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:256)
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter$1.convert(ResultProcessor.java:201)
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:212)
    at org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:149)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:121)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy143.findAllSummarizedBy(Unknown Source)

My classes are the following

DeadlineType

@Data
public class DeadlineType extends DefaultIdAndText {
    @Value("#{target.id}")
    String id;
    @Value("#{target.code}")
    String text;
    @Value("#{target.id}")
    public String getId() {
        return id;
    @Value("#{target.code}")
    public String getText() {
        return text;

ABDeadlineType

@Data
@Entity
@Table(name = "deadline_type")
@AllArgsConstructor
@NoArgsConstructor
public class ABDeadlineType {
    private @Id
    String id;
    private String code;

DefaultIdAndText

@Data @AllArgsConstructor
@NoArgsConstructor
public class DefaultIdAndText implements IdAndText {
    public DefaultIdAndText(IdAndText idAndText){
        this.id = idAndText.getId();
        this.text = idAndText.getText();
    @NotEmpty String id;
    String text;

DeadlineTypeRepository

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<DeadlineType> findAllSummarizedBy();

Update

Could it be an issue that the projection/mapping using @Value("#{target.id}") format, does not work correctly because these have been done on a class and not on an interface???

exception seems OK. Classess are not connected in any way (and DeadlineType is not known to JPA engine). Is this code correctly pasted? BTW give import of Lombok project (or comment in code), snippets will be more intuitive - without few seconds required 'what is this' – Jacek Cz Sep 7, 2017 at 4:15 Not related to the question, but related to your Lombok @Data annotation on your entities. That can be quite dangerous, since it generates an equals, toString and hashcode based on ALL fields of your entity, including any lazy associations... So when you play around with entities outside of a transaction and try to print it out or compare it to another one, it will try to fetch all those lazy associations (outside of a transaction) and throw a LazyInitializationException! – Dieter Hubau Jan 22, 2019 at 10:07 I have a similar problem when I add @NoArgsConstructor to my DTO, but without it -- all works – Anton Mar 19, 2020 at 11:06

Return ABDeadlineType from repository:

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();

and then convert to DeadlineType. Manually or use mapstruct.

Or call constructor from @Query annotation:

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    @Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
    List<DeadlineType> findAllSummarizedBy();

Or use @Projection:

@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {
    @Value("#{target.id}")
    String getId();
    @Value("#{target.code}")
    String getText();

Update: Spring can work without @Projection annotation:

public interface DeadlineType {
    String getId();    
    String getText();
                Don't we have though a mechanism to do this on the fly using projections ? Atleast that's what a colleague mentions those @Valueannotations are for.
– Menelaos
                Sep 7, 2017 at 11:13
                @MenelaosBakopoulos See updated answer. Docs: docs.spring.io/spring-data/rest/docs/current/reference/html/…
– Nick
                Sep 7, 2017 at 11:37
                I would avoid using interface based projections, because they lead to a consumption of more memory comparing to class based projections. If you have a code using queries with thousands of results, like when you are doing migration of data, then memory consumption amount becomes important.
– heroin
                Aug 6, 2019 at 12:49

You may already have this working, but the I created a test project with the classes below allowing you to retrieve the data into an entity, projection or dto.

Projection - this will return the code column twice, once named code and also named text (for example only). As you say above, you don't need the @Projection annotation

import org.springframework.beans.factory.annotation.Value;
public interface DeadlineTypeProjection {
    String getId();
    // can get code and or change name of getter below
    String getCode();
    // Points to the code attribute of entity class
    @Value(value = "#{target.code}")
    String getText();

DTO class - not sure why this was inheriting from your base class and then redefining the attributes. JsonProperty just an example of how you'd change the name of the field passed back to a REST end point

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class DeadlineType {
    String id;
    // Use this annotation if you need to change the name of the property that is passed back from controller
    // Needs to be called code to be used in Repository
    @JsonProperty(value = "text")
    String code;

Entity class

import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@Entity
@Table(name = "deadline_type")
public class ABDeadlineType {
    private String id;
    private String code;

Repository - your repository extends JpaRepository<ABDeadlineType, Long> but the Id is a String, so updated below to JpaRepository<ABDeadlineType, String>

import com.example.demo.entity.ABDeadlineType;
import com.example.demo.projection.DeadlineTypeProjection;
import com.example.demo.transfer.DeadlineType;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, String> {
    List<ABDeadlineType> findAll();
    List<DeadlineType> findAllDtoBy();
    List<DeadlineTypeProjection> findAllProjectionBy();

Example Controller - accesses the repository directly to simplify code

@RequestMapping(value = "deadlinetype")
@RestController
public class DeadlineTypeController {
    private final ABDeadlineTypeRepository abDeadlineTypeRepository;
    @Autowired
    public DeadlineTypeController(ABDeadlineTypeRepository abDeadlineTypeRepository) {
        this.abDeadlineTypeRepository = abDeadlineTypeRepository;
    @GetMapping(value = "/list")
    public ResponseEntity<List<ABDeadlineType>> list() {
        List<ABDeadlineType> types = abDeadlineTypeRepository.findAll();
        return ResponseEntity.ok(types);
    @GetMapping(value = "/listdto")
    public ResponseEntity<List<DeadlineType>> listDto() {
        List<DeadlineType> types = abDeadlineTypeRepository.findAllDtoBy();
        return ResponseEntity.ok(types);
    @GetMapping(value = "/listprojection")
    public ResponseEntity<List<DeadlineTypeProjection>> listProjection() {
        List<DeadlineTypeProjection> types = abDeadlineTypeRepository.findAllProjectionBy();
        return ResponseEntity.ok(types);

Hope that helps

Hello Les Wilson. This works perfectly for methods already ready and managed by Spring Data, such as "findAll". But if I need to create any query with @Query the error below occurs: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type. I managed to use it by creating something with "@"Query with just an interface instead of DTO. Do you know if it is possible to create my own "@"Query? Thanks. – Eduardo Ronaldo Mar 1, 2021 at 2:50

I have met the same problem recently with spring-data-jpa:2.5.0.

Solution (for queries with no @Query annotation):

For class-based projection (DTOs), the problem is the @NoArgsConstructor in the DTO class. Revemoving it should make things work.

Something interesting I found during debug:

With the presence of a non argument constructor, the returnedType somehow was created with 0 input properties.

When a query is actually created, JpaQueryCreator (spring-data-jpa) would check if it needs to do custom construction according to the number of input properties.

As it's not the case with 0 input properties, it would then return the whole entity instance.

https://github.com/spring-projects/spring-data-jpa/blob/main/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryCreator.java#L169

Finally when the result is being returned, the target type and returned type don't match, as there is no converter available to convert from the entity instance to the projectiong dto. The error was thrown.

https://github.com/spring-projects/spring-data-commons/blob/main/src/main/java/org/springframework/data/repository/query/ResultProcessor.java#L162

"For class-based projection (DTOs), the problem is the @NoArgsConstructor in the DTO class. Revemoving it should make things work." This one really helps. Verified with SpringBoot 2.7.3. – dashtinejad Aug 22, 2022 at 20:27 YES! That simple: the problem is the @NoArgsConstructor in the DTO class! Thx! (Spring Boot 2.7.6) – t0r0X Dec 6, 2022 at 22:21

use {nativeQuery=true} in your query.

for example

  @Query(value = "select d.id,d.name,d.breed,d.origin from Dog d",nativeQuery = true)
    List<Dog> findALL();

If you look at the exception stack trace it says that, it failed to convert from ABDeadlineType to DeadlineType. Because your repository is going to return you the objects of ABDeadlineType. How the spring-data-jpa will convert into the other one(DeadlineType). You should return the same type from repository and then have some intermediate util class to convert it into your model class.

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();

Turns out, when the table name is different than the model name, you have to change the annotations to:

@Entity
@Table(name = "table_name")
class WhateverNameYouWant {

Instead of simply using the @Entity annotation.

What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.

If you want to use DTO rather than Entity in List that is easy just create Interface and replace it with DTO in List.

Example:

@Query(value = "select id, age, name FROM Person WHERE age=?1", nativeQuery=true)
List<PersonView> getPersonsByAge(int age);

and an interface

public interface PersonView {
    Long getId();
    Integer getAge();
    String getName();

Well I have another answer I have used Interfaces for Projections and Classes for Dto's and I am using ModelMapper to map my Projections to Dto Class So my 1 Dto class may have many Projections which can mapped to Dto and used to Taste

gradle implementation 'org.modelmapper:modelmapper:3.1.0'

   @Autowired
    private ModelMapper modelMapper;
List<UserDto> usersdto = repository.findUserByRoleName().stream().map(userprojection -> modelMapper.map(userprojection, UserDto.class))
                    .collect(Collectors.toList());

My projection is like this

public interface UserProjection {
     String getId();    
     String getEmail(); 

My dto is

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDto {
    private long id;
    private String firstName;
    private String lastName;
    private String phone;
    private String email;

And I am able to get fields from custom queries

For example:

In your code, the repository where you placed you query extends JpaRepository that with class and id type <ABDeadlineType, Long>. So it expects to return ABDeadlineType data.

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<DeadlineType> findAllSummarizedBy();

As you want to get DeadlineType data, you should keep your query in such repository like

public interface DeadlineTypeRepository extends JpaRepository<DeadlineType, Long>

So, either replace the class name inside JpaRepository<> Or place your query in another repository. Then you don't need to do any mapping or write extra codes for it.

In my case, it worked.

For me projection solve this problem here is the code segments. this is the native query for this example

SELECT cifno,accnbr FROM institutedb.customerWHERE id = 100200

Step 1: First Create a Entity class relevant to any table

@Entity
@Table(name = "customer", schema = "institutedb")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class CustomerEntity {
    private int id;
    private BigInteger accnbr;
    private String actdate;
    private int active;

Step2: Then clean projection interface and DTO class. keep remind the interface getter method should have naming convention is DTO properties has got.

Projection Interface

   public interface CustomerProjection {
        String getCifno();
        String getAccnbr();

DTO Class

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class CustomerDTO {
    private String cifno;
    private String accnbr;

Step 3:

Next create the repository to embed the native query

public interface CustomerModelReporsitoy  extends JpaRepository<CustomerEntity,String> {
    @Query(
            value = "SELECT cifno,accnbr FROM institutedb.customerWHERE id = 100200",
            nativeQuery = true
    List<CustomerProjection> findCifByUserName();

Step 4:

Create a get mapping for testing purpose and access the repo method

@GetMapping("/custmodel")
    public String getCifModel(){
        ModelMapper modelMapper = new ModelMapper();
        List<CustomerProjection> collect = customerModelReporsitoy.findCifByUserName().stream().map(customerProjection -> modelMapper.map(customerProjection, CustomerProjection.class))
                .collect(Collectors.toList());
        collect.stream().forEach((cust)-> {
            System.out.println(cust.getCifno());
            System.out.println(cust.getAccnbr());
        return "cif";

As a work around Solution for those who can not determine how the required object will be returned back

i used this way and it fits with native query

@Query(" what ever query " , nativeQuery = true) List<Map<String, Object>> getAllExportData() ;

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.