当前位置: 首页 > 知识库问答 >
问题:

是否有方法在JPA查询中从数据库中选择特定列

谷弘致
2023-03-14

我正在尝试执行一个JPA SQL查询以从数据库中选择特定列(查询:'select username,ranking_points_sum from user order by ranking_points_sum ASC')。

我的用户实体:

@Entity
@Table
public class User {

  @Id
  @GeneratedValue
  private int id;

  private String firstname;
  private String lastname;
  private String username;
  private int rankingPointsSum;
  private String email;
  private String password;

  @ManyToMany
  private List<Role> roles;

  private String token;

  @ManyToOne
  private Team team;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFirstname() {
    return firstname;
  }

  public void setFirstname(String firstname) {
    this.firstname = firstname;
  }

  public String getLastname() {
    return lastname;
  }

  public void setLastname(String lastname) {
    this.lastname = lastname;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public int getRankingPointsSum() {
    return rankingPointsSum;
  }

  public void setRankingPointsSum(int rankingPointsSum) {
    this.rankingPointsSum = rankingPointsSum;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public Team getTeam() {
    return team;
  }

  public void setTeam(Team team) {
    this.team = team;
  }

  public List<Role> getRoles() {
    return roles;
  }

  public void setRoles(List<Role> roles) {
    this.roles = roles;
  }

  public String getToken() {
    return token;
  }

  public void setToken(String token) {
    this.token = token;
  }
}

我的JPA存储库:

public interface UserRepository extends CrudRepository<User, Integer> {
  User findByUsername(String username);

  @Query(value = "SELECT username, ranking_points_sum from user order by ranking_points_sum ASC", nativeQuery = true)
  List<User> getRankingList();
}
  @CrossOrigin(origins = "http://localhost:8081") // only for dev purpose
  @RequestMapping("/api/getRankingList")
  @ResponseBody
  String getRankingList() {
    return new Gson().toJson(userRepository.getRankingList());
  }
Sun Mar 31 14:21:33 CEST 2019
There was an unexpected error (type=Internal Server Error, status=500).
could not execute query; SQL [SELECT username, ranking_points_sum from user order by ranking_points_sum ASC]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [SELECT username, ranking_points_sum from user order by ranking_points_sum ASC]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:279)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy101.getRankingList(Unknown Source)
    at hhn.labsw.bugageocaching.controller.Controller.getRankingList(Controller.java:309)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.loader.Loader.doList(Loader.java:2692)
    at org.hibernate.loader.Loader.doList(Loader.java:2672)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2506)
    at org.hibernate.loader.Loader.list(Loader.java:2501)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:2223)
    at org.hibernate.internal.AbstractSharedSessionContract.list(AbstractSharedSessionContract.java:1053)
    at org.hibernate.query.internal.NativeQueryImpl.doList(NativeQueryImpl.java:170)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505)
    at org.hibernate.query.Query.getResultList(Query.java:135)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:129)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    ... 64 more
Caused by: java.sql.SQLSyntaxErrorException: No such column: id
    at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:236)
    at org.mariadb.jdbc.internal.com.read.dao.ColumnNameMap.getIndex(ColumnNameMap.java:133)
    at org.mariadb.jdbc.internal.com.read.resultset.SelectResultSet.findColumn(SelectResultSet.java:1484)
    at org.mariadb.jdbc.internal.com.read.resultset.SelectResultSet.getInt(SelectResultSet.java:1062)
    at com.zaxxer.hikari.pool.HikariProxyResultSet.getInt(HikariProxyResultSet.java)
    at org.hibernate.type.descriptor.sql.IntegerTypeDescriptor$2.doExtract(IntegerTypeDescriptor.java:62)
    at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:261)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:247)
    at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:333)
    at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:793)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:718)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:990)
    at org.hibernate.loader.Loader.doQuery(Loader.java:948)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340)
    at org.hibernate.loader.Loader.doList(Loader.java:2689)
    ... 87 more

如果我更改JPA存储库查询,从数据库中选择所有内容,如下所示:

public interface UserRepository extends CrudRepository<User, Integer> {
  User findByUsername(String username);

  @Query(value = "SELECT * from user order by ranking_points_sum ASC", nativeQuery = true)
  List<User> getRankingList();
}

我没有发现任何错误。“http://localhost:8080/api/getrankinglist”现在将我的数据库表作为JSON返回:

// 20190331142532
// http://localhost:8080/api/getRankingList

[
  {
    "id": 1,
    "firstname": "Timo",
    "lastname": "Volkmann",
    "username": "moximoti",
    "rankingPointsSum": 0,
    "email": "test@user.com",
    "password": "$2a$10$c3Fo5nuUG.nlwXP94qc7qO01/UC1OL2DebEm.5zYlisKJGRhXMnqq",
    "roles": [
      {
        "id": 0,
        "name": "admin"
      }
    ],
    "token": "$2a$10$3hIZTTN/96h8LU0tEF/em.mhTZr8e14oug94JjOknRtDMMHZc/doK"
  }
]

问题是,我不需要整个数据库表,我只需要作为JSON返回的这两个列(username、ranking_points_sum)。

那么,有没有办法做到这一点呢?

共有1个答案

卓俊晖
2023-03-14

异常消息显示no such column:id。这意味着,无论您从数据库获取什么,都没有实体映射所需的字段。

换句话说,您不能执行以下操作:

"SELECT username, ranking_points_sum from user order by ranking_points_sum ASC"

假设结果是user的列表,因为user实体具有需要作为查询结果的字段,如id。这也是使用*的相同查询工作的原因-所有列都是FETCHE,所有字段都是映射的。

 类似资料:
  • 问题内容: 是否可以检索中特定行的特定列? 假设我要使用以下查询文本从名为的表中选择名称为:a,b的行: 如何修改此查询文本以仅选择第2、12、22、32、42列,而不是选择其所有1000列? 问题答案: 将通配符替换为要检索的列名。 但是请阅读有关SQL标准的文档。您在表中需要1.000列的可能性很小。

  • 我想在接口中添加一个用于以下SQL查询的方法: 这个SQL查询按预期工作,但我想把它写成一个JPA查询方法,我尝试了很多方法但都没有让它工作,请帮助我。 接下来我试过了,但没有成功:

  • 问题内容: 我想在进行Web服务调用之前检查数据库中是否已记录的记录。 这是我想像的查询形式,我似乎无法弄清楚语法。 有没有办法做到这一点?这样的查询叫什么? 我想将ID的列表传递给mysql,并希望它吐出数据库中尚未存在的ID? 问题答案: 为了确认我已正确理解,您想传递一个数字列表,并查看现有表中 不 存在哪些数字?有效: 您似乎可以随时建立此查询,在这种情况下,可以通过将上面的代码更改为 尽

  • 我尝试编写一些常用方法(Java/Spring/JPA)从数据库中获取前N个实体。所有实体都有@Id注释,但Id字段可以有各种名称。例如,ID为表的实体。tableId或板。平板。tableId和plateId都有注释,但字段名不同(在代码和数据库中)。我无法更改字段名。我试图通过JPA标准API对asc和setMaxResults进行排序,但找不到按id排序的方法。 我需要使用什么使asc按id

  • 但是我在遗留系统上有一个具有许多属性的对象,我只想选择几个,尽管我知道选择几个属性通常是很快的。 如果不使用条件查询,这可能吗?

  • 问题内容: 我想知道如何检查数据库中的特定表(例如:myTable)中是否存在特定列(例如:日期)。 我已经阅读了此答案,该答案提供了一个查询,该查询导致另一个查询。 但是我需要的是结果。 更新1 如何在C#应用程序中做到这一点? 也许使用或其他? 问题答案: 感谢所有提供解决方案并收集了一些答案的人,我提出了自己的解决方案版本。也许这不是最好的解决方案,但是至少我不需要额外的dll来添加引用或处