我使用Spring JPA执行所有数据库操作。但是,我不知道如何从Spring JPA的表中选择特定的列?
例如: SELECT projectName FROM projects
我使用Spring JPA执行所有数据库操作。但是,我不知道如何从Spring JPA的表中选择特定的列?
例如: SELECT projectName FROM projects
当前回答
在我的情况下,我创建了一个单独的实体类,没有字段是不需要的(只有字段是必需的)。
将实体映射到同一个表。 现在当所有的列都是必需的,我使用旧的实体,当只有一些列是必需的,我使用lite实体。
如。
@Entity
@Table(name = "user")
Class User{
@Column(name = "id", unique=true, nullable=false)
int id;
@Column(name = "name", nullable=false)
String name;
@Column(name = "address", nullable=false)
Address address;
}
你可以创建如下内容:
@Entity
@Table(name = "user")
Class UserLite{
@Column(name = "id", unique=true, nullable=false)
int id;
@Column(name = "name", nullable=false)
String name;
}
当您知道要获取的列时,这是有效的(这不会改变)。
如果你需要动态地决定列,这是行不通的。
其他回答
在我的情况下,我创建了一个单独的实体类,没有字段是不需要的(只有字段是必需的)。
将实体映射到同一个表。 现在当所有的列都是必需的,我使用旧的实体,当只有一些列是必需的,我使用lite实体。
如。
@Entity
@Table(name = "user")
Class User{
@Column(name = "id", unique=true, nullable=false)
int id;
@Column(name = "name", nullable=false)
String name;
@Column(name = "address", nullable=false)
Address address;
}
你可以创建如下内容:
@Entity
@Table(name = "user")
Class UserLite{
@Column(name = "id", unique=true, nullable=false)
int id;
@Column(name = "name", nullable=false)
String name;
}
当您知道要获取的列时,这是有效的(这不会改变)。
如果你需要动态地决定列,这是行不通的。
在更新的Spring版本中,你可以这样做:
如果不使用本机查询,可以这样做:
public interface ProjectMini {
String getProjectId();
String getProjectName();
}
public interface ProjectRepository extends JpaRepository<Project, String> {
@Query("SELECT p FROM Project p")
List<ProjectMini> findAllProjectsMini();
}
使用本机查询也可以这样做:
public interface ProjectRepository extends JpaRepository<Project, String> {
@Query(value = "SELECT projectId, projectName FROM project", nativeQuery = true)
List<ProjectMini> findAllProjectsMini();
}
详情请查看文档
{
"Comments":"Why not using JDBCTemplate",
"Url":"https://www.baeldung.com/spring-jdbc-jdbctemplate"
}
在本地sql中可以指定null作为字段值。
@Query(value = "select p.id, p.uid, p.title, null as documentation, p.ptype " +
" from projects p " +
"where p.uid = (:uid)" +
" and p.ptype = 'P'", nativeQuery = true)
Project findInfoByUid(@Param("uid") String uid);
你可以使用JPQL:
TypedQuery <Object[]> query = em.createQuery(
"SELECT p.projectId, p.projectName FROM projects AS p", Object[].class);
List<Object[]> results = query.getResultList();
或者您可以使用本地SQL查询。
Query query = em.createNativeQuery("sql statement");
List<Object[]> results = query.getResultList();