Spring Boot JPA如何从带有实体类的表中选择特定的列? [英] Spring Boot JPA how to select specific column from table with the entity class?
问题描述
我正在使用spring boot JPA进行数据库操作.在我的实体类中,我将每个列与表进行映射.在我的表中,我有很多列,但是我需要在查询结果集中选择其中的一些.我不需要执行select * from table_name
即可将性能问题带到我的应用程序中.
In am using spring boot JPA for my database operations. In my entity class, I mapped every columns with my table. In my table I have many columns, but I need to select some of them in my query result set. I does not need to do select * from table_name
which brings the performance issue to my application.
我的实体类:
@Entity
@Table(name = "user_table")
public class UserInformation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private int userId;
@Column(name = "user_name")
private String userName;
@Column(name = "user_type")
private String userType;
@Column(name = "user_age")
private int userAge;
@Column(name = "is_male")
private boolean isMale;
}
此后,我生成了上述类的所有吸气剂和吸气剂.
After this I generated all getters and setters for above class.
我的userDAO类
public interface UserInformationRepo extends
JpaRepository<UserInformation, String>{
@Query(value="select user_name from user_table where user_age >
:userAge", nativeQuery=true)
public UserInformation getInfo(int userAge);\
@Query(value="select user_name,userType, user_id from user_table where
user_age > :userAge", nativeQuery=true)
public UserInformation getInfo(int userAge);
}
当我使用上述类运行此春季启动应用程序时,它显示错误为
When I run this spring boot app with my above class it shows error as
user_id未包含在结果集中
user_id was not included in the ResultSet
此错误是因为我没有从查询中选择user_id.
This error because I did't select the user_id from my query.
在我的userDAO类中,我有多个函数,每个函数需要不同的列集,但是所有方法的返回类型应该是UserInformation类.
In my userDAO class I have a multiple functions, each functions need different set of columns, but the return type of all methods should be UserInformation class.
我的例外结果是,我未从查询中选择的列在我的结果UserInformation对象中应为空值.
My excepted result is, the columns which I does not select from query should have null value in my result UserInformation object.
我也为此搜索了很多资源,但是找不到任何相关的答案.
I also searched many resources for this, but I cannot find any relevant answer.
任何帮助.预先感谢
推荐答案
一种方法是使用userId
和userName
创建UserInformation
的构造函数.
One way could be create a constructor of the UserInformation
with userId
and userName
.
package com.demo.model;
public UserInformation( String userName, String userType, String userId){
this.userName = userName;
this.userType = userType;
this.userId = userId;
}
然后
@Query(value="select new com.demo.model.UserInformation
(user_name,userType, user_id)
from user_table where
user_age > :userAge", nativeQuery=true)
这篇关于Spring Boot JPA如何从带有实体类的表中选择特定的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!