【问题标题】:Can't update a field in a PostgreSQL table无法更新 PostgreSQL 表中的字段
【发布时间】:2019-08-14 10:32:22
【问题描述】:

我正在尝试建立一个类似 Stack Overflow 的问答网站,以了解 RESTful Web 服务的工作原理,这是我第一次编写 Web 服务,我已经制作了用于提问和回答问题的控制器。

但是有一个问题,我在为 upvote 制作 REST Endpoint 时遇到了这个问题,所以每当用户提出问题时,我都必须更新问题表中的投票数(在开始时为零)但是当我尝试点击 Endpoint for Upvote 时,我编写的更新查询会引发错误并显示错误页面。

抛出的错误:

org.postgresql.util.PSQLException: No results were returned by the query.
    at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:107) ~[postgresql-42.2.5.jar:42.2.5]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.2.0.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2167) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1930) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1892) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.loader.Loader.doQuery(Loader.java:937) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.loader.Loader.doList(Loader.java:2689) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.loader.Loader.doList(Loader.java:2672) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2506) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.loader.Loader.list(Loader.java:2501) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:2223) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.internal.AbstractSharedSessionContract.list(AbstractSharedSessionContract.java:1069) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.query.internal.NativeQueryImpl.doList(NativeQueryImpl.java:170) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.query.internal.AbstractProducedQuery.getSingleResult(AbstractProducedQuery.java:1553) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:221) ~[spring-data-jpa-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91) ~[spring-data-jpa-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136) ~[spring-data-jpa-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125) ~[spring-data-jpa-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:138) ~[spring-data-jpa-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at com.sun.proxy.$Proxy100.vote(Unknown Source) ~[na:na]
    at com.demo.beans.controller.QuestionController.upvoteQuestion(QuestionController.java:222) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:151) ~[spring-session-core-2.1.7.RELEASE.jar:2.1.7.RELEASE]
    at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:85) ~[spring-session-core-2.1.7.RELEASE.jar:2.1.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]

用于更新投票的 QuestionRepository 代码:

package com.demo.beans.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.demo.beans.Question;

@Repository
public interface QuestionRepository extends JpaRepository<Question, Long> {

    @Query(value = "SELECT * from questions where pr_key=:pr_key", nativeQuery = true)
    public Question findByPrKey(@Param("pr_key") String prKey);

    @Query(value = "UPDATE questions SET questionvotes=:questionvotes where pr_key=:pr_key", nativeQuery=true)
    public void changeVotes(@Param("questionvotes") int questionVotes, @Param("pr_key") String prKey);
}

这里第二个查询负责更新投票。

我在 QuestionsController 中用这个方法调用这个函数:

@RequestMapping("/upvoteQuestion")
    public String upvoteQuestion(@CookieValue(value = "username", defaultValue = "null") String username,
            @CookieValue(value = "password", defaultValue = "null") String password, @Valid QuestionVote questionVote) {

        System.out.println("works" + questionVote.getQuestionPrKey() + " " + questionVote.getUserPrKey());

        if (!username.equals("null") && !password.equals("null")) {

            // checks whether there is user with the username and password given
            // by the cookie
            if (userRepository.checkWhetherAccountExists(username, password).get(0) != null) {

                questionVote.setUserPrKey(userRepository.findUsingUsername(username).getPrKey());

                if (questionVoteRepository.checkUpvote(questionVote.getQuestionPrKey(), questionVote.getUserPrKey()).equals("false")) {

                    questionVoteRepository.vote("true", "false", questionVote.getQuestionPrKey(),questionVote.getUserPrKey());
                    System.out.println("Question PrKey: " + questionVote.getQuestionPrKey());
                    questionRepository.changeVotes(13, questionVote.getQuestionPrKey());

                }

            }
        }

        return "redirect:/questions/"+questionVote.getQuestionPrKey();
    }

在上面的代码中,下面一行抛出了错误:

questionRepository.changeVotes(13, questionVote.getQuestionPrKey());

我的问题类如下所示:

package com.demo.beans;

import java.sql.Time;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "questions")
public class Question {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(name = "PR_KEY")
    private String prKey;

    @Column(name = "postedby")
    private String postedBy; // pr_key of the person who posted the question

    @Column(name = "postedbyusername")
    private String postedByUsername; // username of the person who posted the
                                        // question

    @Column(name = "title", columnDefinition = "varchar(1000)")
    private String title; // title of the question

    @Column(name = "content", columnDefinition = "varchar(10000)")
    private String content; // content of the question

    @Column(name = "code", columnDefinition = "varchar(10000)")
    private String code; // code (if included) of the question

    @Column(name = "viewscount")
    private int views_count; // views count of the question

    @Column(name = "answercount")
    private int answer_count; // answers count of the question

    @Column(name = "tag")
    private String tag; // tag which a question is tagged

    @Column(name = "questionaskedtime")
    private String questionAskedTime; // time at which the question was asked

    @Column(name = "questionlastactivetime")
    private String questionLastActiveTime; // time at which the question was
                                            // active the last time

    @Column(name = "questionvotes")
    private int questionVotes; // number of votes on the question

    @Column(name = "acceptedanswerstatus")
    private String acceptedAnswerStatus; // whether the question has an accepted
                                            // answer

    @Column(name = "questionlink")
    private String questionLink;

    public Question() {

    }

    public Question(String postedBy, String title, String content, String code, int views_count, int answer_count,
            String tag, String questionAskedTime, String questionLastActiveTime, int questionVotes,
            String acceptedAnswerStatus, String questionLink, String postedByUsername) {
        super();
        this.title = title;
        this.content = content;
        this.code = code;
        this.views_count = views_count;
        this.answer_count = answer_count;
        this.tag = tag;
        this.questionAskedTime = questionAskedTime;
        this.questionLastActiveTime = questionLastActiveTime;
        this.questionVotes = questionVotes;
        this.acceptedAnswerStatus = acceptedAnswerStatus;
        this.questionLink = questionLink;
        this.postedByUsername = postedByUsername;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public int getViews_count() {
        return views_count;
    }

    public void setViews_count(int views_count) {
        this.views_count = views_count;
    }

    public int getAnswer_count() {
        return answer_count;
    }

    public void setAnswer_count(int answer_count) {
        this.answer_count = answer_count;
    }

    public String getTags() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public String getQuestionAskedTime() {
        return questionAskedTime;
    }

    public void setQuestionAskedTime(String questionAskedTime) {
        this.questionAskedTime = questionAskedTime;
    }

    public String getQuestionLastActiveTime() {
        return questionLastActiveTime;
    }

    public void setQuestionLastActiveTime(String questionLastActiveTime) {
        this.questionLastActiveTime = questionLastActiveTime;
    }

    public int getQuestionVotes() {
        return questionVotes;
    }

    public void setQuestionVotes(int questionVotes) {
        this.questionVotes = questionVotes;
    }

    public String getAcceptedAnswerStatus() {
        return acceptedAnswerStatus;
    }

    public void setAcceptedAnserStatus(String acceptedAnswerStatus) {
        this.acceptedAnswerStatus = acceptedAnswerStatus;
    }

    public String getPrKey() {
        return prKey;
    }

    public void setPrKey(String prKey) {
        this.prKey = prKey;
    }

    public String getPostedByUsername() {
        return postedByUsername;
    }

    public void setPostedByUsername(String postedByUsername) {
        this.postedByUsername = postedByUsername;
    }

    public String getQuestionLink() {
        return questionLink;
    }

    public void setQuestionLink(String questionLink) {
        this.questionLink = questionLink;
    }

}


是的,我在表格中有数据。我做错了什么,我该如何解决?

我也尝试过添加@Modifying,但仍然抛出同样的错误。

编辑

我使用 UPDATE Query 更新了不同表中的其他字段,它可以工作,不知道为什么这不起作用。

questionVoteRepository.vote("true", "false", questionVote.getQuestionPrKey(),questionVote.getUserPrKey());

在上面添加的方法 upvoteQuestion 中检查上面的代码行,这行代码完美,更新了 question_votes 表。

QuestionVote POJO 如下所示:

package com.demo.beans;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="question_votes")
public class QuestionVote {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(name = "PR_KEY")
    private String prKey;

    @Column(name="question_pr_key")
    private String questionPrKey;

    @Column(name="user_pr_key")
    private String userPrKey;

    @Column(name="upvote")
    private String upvote;

    @Column(name="downvote")
    private String downvote;

    public QuestionVote() {

    }

    public QuestionVote(String prKey, String questionPrKey, String userPrKey, String upvote, String downvote) {
        super();
        this.prKey = prKey;
        this.questionPrKey = questionPrKey;
        this.userPrKey = userPrKey;
        this.upvote = upvote;
        this.downvote = downvote;
    }

    public String getPrKey() {
        return prKey;
    }

    public void setPrKey(String prKey) {
        this.prKey = prKey;
    }

    public String getQuestionPrKey() {
        return questionPrKey;
    }

    public void setQuestionPrKey(String questionPrKey) {
        this.questionPrKey = questionPrKey;
    }

    public String getUserPrKey() {
        return userPrKey;
    }

    public void setUserPrKey(String userPrKey) {
        this.userPrKey = userPrKey;
    }

    public String getUpvote() {
        return upvote;
    }

    public void setUpvote(String upvote) {
        this.upvote = upvote;
    }

    public String getDownvote() {
        return downvote;
    }

    public void setDownvote(String downvote) {
        this.downvote = downvote;
    }
}

添加问题后,我也在 question_votes 表中添加一行,并将该行的 upvote 和 downvote 列设置为 false、false。当问题被投票时,我更新了questionsquestion_votes 这两个表,question_votes 表更新成功,但 questions 表没有更新。

QuestionVoteRepository 如下所示:

package com.demo.beans.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.demo.beans.QuestionVote;



@Repository
public interface QuestionVoteRepository extends JpaRepository<QuestionVote, Long>{

    @Query(value = "SELECT exists (SELECT 1 from question_votes where question_pr_key=:question_pr_key and user_pr_key=:user_pr_key)", nativeQuery=true)
    public String checkWhetherRowExists(@Param("question_pr_key") String questionPrKey,
            @Param("user_pr_key") String userPrKey);


    @Query(value = "SELECT upvote from question_votes where question_pr_key=:question_pr_key and user_pr_key=:user_pr_key", nativeQuery=true)
    public String checkUpvote(@Param("question_pr_key") String questionPrKey, @Param("user_pr_key") String userPrKey);

    @Query(value = "SELECT downvote from question_votes where question_pr_key=:question_pr_key and user_pr_key=:user_pr_key", nativeQuery=true)
    public String checkDownvote(@Param("question_pr_key") String questionPrKey, @Param("user_pr_key") String userPrKey);

    @Query(value = "UPDATE question_votes SET upvote=:upvote, downvote=:downvote where question_pr_key=:question_pr_key and user_pr_key=:user_pr_key", nativeQuery=true)
    public void vote(@Param("upvote") String upvote, @Param("downvote") String downvote,
            @Param("question_pr_key") String questionPrKey, @Param("user_pr_key") String userPrKey);


}

【问题讨论】:

  • 尝试使用PgPreparedStatement.execute() 而不是executeQuery(),因为UPDATE 不是查询,它是更新语句,不会返回任何行。
  • @deHaar 我在同一代码中使用了 UPDATE 语句来更新不同表中的其他字段,它工作正常,唯一的区别是在那个表中我正在更新一个字符串,但它是int,我不明白为什么这不起作用。
  • 那么请在您的问题中编辑两个示例:一个不起作用,一个起作用。我们需要看看两者的数据访问代码。
  • 好的,谢谢,但我看不到任何对 PgPreparedStatement.executeQuery() 的呼叫。你只有带注释的方法吗?后面是什么?如果您尚未对数据库访问进行编码,则可能必须使用不同的注释或其他注释。
  • 看起来您必须在 @AhmedAbdelhady 回答时添加 @Modifying 注释。您也可以添加@Transactional,但我真的不知道这是否会改变任何事情。我认为@Modifying 将在内部使用PgPreparedStatement 的正确方法。

标签: java spring postgresql hibernate spring-boot


【解决方案1】:

您需要将@Modifying 添加到存储库中的changeVotes 方法中,以标记这是一个更新查询,预计不会返回任何结果。

https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/Modifying.html

【讨论】:

  • 我也加了@Modifying,还是报同样的错误。
  • 我认为你还需要在upvoteQuestion控制器方法中添加@Transactional
  • @Transactional 来自 javax.transaction 或来自 org.springframework.transaction.annotation ?
  • org.springframework.transaction.annotation.Transactional
  • 很难判断还有什么问题,如果可能的话,共享存储库,如果它是公开的,以便其他人可以签出代码并自己尝试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
  • 2015-09-23
  • 2013-07-22
相关资源
最近更新 更多