带有投影的 Spring JPA 本机查询给出了“ConverterNotFoundException"; [英] Spring JPA native query with Projection gives "ConverterNotFoundException"
问题描述
我正在使用 Spring JPA,我需要一个本机查询.通过该查询,我只需要从表中获取两个字段,因此我尝试使用 投影.它不起作用,这是我收到的错误:
I'm using Spring JPA and I need to have a native query. With that query, I need to get only two fields from the table, so I'm trying to use Projections. It isn't working, this is the error I'm getting:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.example.IdsOnly]
我试图完全按照我链接的那个页面的说明进行操作,我试图使我的查询非本地(顺便说一句,如果我使用投影,我真的需要它是本地的吗?),但我总是得到那个错误.
如果我使用一个接口,它可以工作,但结果是代理,我真的需要它们是我可以变成 json 的正常结果".
I tried to follow precisely the instructions of that page I linked, I tried to make my query non-native (do I actually need it to be native if I use projections, btw?), but I always get that error.
If I use an interface it works, but the results are proxies and I really need them to be "normal results" that I can turn into json.
所以,这是我的代码.实体:
So, here's my code. The Entity:
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@Entity
@Table(name = "TestTable")
public class TestTable {
@Id
@Basic(optional = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "Id")
private Integer id;
@Column(name = "OtherId")
private String otherId;
@Column(name = "CreationDate")
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
@Column(name = "Type")
private Integer type;
}
投影的类:
import lombok.Value;
@Value // This annotation fills in the "hashCode" and "equals" methods, plus the all-arguments constructor
public class IdsOnly {
private final Integer id;
private final String otherId;
}
存储库:
public interface TestTableRepository extends JpaRepository<TestTable, Integer> {
@Query(value = "select Id, OtherId from TestTable where CreationDate > ?1 and Type in (?2)", nativeQuery = true)
public Collection<IdsOnly> findEntriesAfterDate(Date creationDate, List<Integer> types);
}
以及试图获取数据的代码:
And the code that tries to get the data:
@Autowired
TestTableRepository ttRepo;
...
Date theDate = ...
List<Integer> theListOfTypes = ...
...
Collection<IdsOnly> results = ttRepo.findEntriesAfterDate(theDate, theListOfTypes);
感谢您的帮助.我真的不明白我做错了什么.
Thanks for the help. I really don't understand what I'm doing wrong.
推荐答案
有了spring data,你就可以省去中间人,简单定义
with spring data you can cut the middle-man and simply define
public interface IdsOnly {
Integer getId();
String getOtherId();
}
并使用本机查询,如;
@Query(value = "Id, OtherId from TestTable where CreationDate > ?1 and Type in (?2)", nativeQuery = true)
public Collection<IdsOnly> findEntriesAfterDate(Date creationDate, List<Integer> types);
查看https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections
这篇关于带有投影的 Spring JPA 本机查询给出了“ConverterNotFoundException";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!