我有一个实体类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
查询,并将结果映射到另外一个Entity
类UserStatisticsModel.java
@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
答案 0 :(得分:1)
您的查询是个问题。您说Select 1 as id
但是您要返回UserStatisticsModel
。因此,您必须修改查询或更改方法签名以返回Integer
。