我有一个实体类UserModel.java
@Entity
@Table
@Data
@EqualsAndHashCode( of = { "id" } )
@ToString( of = { "id" } )
public class UserModel {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
@Column( name = "u_id" )
private Long id;
@Column( name = "u_first_name" )
private String firstName;
@Column( name = "u_last_name" )
private String lastName;
@Column( name = "u_email_id" )
private String emailId;
@Column( name = "u_password" )
private String password;
@Column( name = "u_mobile_number" )
private String mobileNumber;
@Column( name = "u_created_at" )
private Calendar createdAt;
@Column( name = "u_is_active" )
private Boolean isActive;
@Column( name = "u_reason" )
private String reason;
}
我需要基于每列中包含的值来获取一些统计数据。所以我创建了一个 JPQL
查询,并将结果映射到一个名为 UserStatisticsModel.java
的另一个 Entity
类。
@Data
@Entity
public class UserStatisticsModel {
@Id
@Column
private Integer id;
@Column
private Integer activeUsers;
@Column
private Integer suspendedUsers;
@Column
private Integer removedUser;
}
我创建了一个仓库类来执行查询。
public interface UserStatisticsRepository extends JpaRepository<UserStatisticsModel, Integer> {
@Query( " Select sum(case when u.isActive is true then 1 else 0 end) as activeUsers, "
+ " sum(case when u.isSuspended is true then 1 else 0 end) as suspendedUsers, "
+ " sum(case when u.isActive is false then 1 else 0 end) as removedUser"
+ " from UserModel u " + " where u.accountStatus <>5" )
UserStatisticsModel getUserStatistics();
但是在执行查询时,我遇到了异常。虽然根据日志记录,查询已经执行并且值是正确的,但是映射失败了。
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.Integer] to type [com.highpeak.tlp.datastore.model.UserStatisticsModel]
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.ArrayToObjectConverter.convert(ArrayToObjectConverter.java:66)
at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:37)
... 125 common frames omitted
有人能解释一下这个错误是什么以及如何修复吗?
可用的解决方案:
我可以在
UserModel.java
中创建那些字段,但我不想在那个类中创建那些字段。我也可以创建一个本地查询,它会起作用。
更新
如果我将查询的返回类型更改为List<Integer>
,我就不会收到任何异常,并且我会得到正确的结果。但是为什么我不能将这些整数映射到我的@Entity
类UserStatisticsmodel.java
的字段中呢?
@Query
上设置nativeQuery=true
。 - Roddy of the Frozen PeasJPQL
。 - Naanavanalla