RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-277129

Orkhan Hasanli's questions

Martin Hope
Orkhan Hasanli
Asked: 2020-06-19 01:56:31 +0000 UTC

为什么通过flyway迁移数据库时序列没有更新?

  • 1

下面是一个简单的例子: 使用的数据库是 PostgresSQL。使用的堆栈:Spring Boot + Hibernate + FlyWay

@数据

@Entity
@Table(name = "books")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long bookId;

    //....
}

这是hibernate生成的表

create table if not exists books
(
  book_id bigserial not null
    constraint books_pkey
      primary key,
  language_id bigint
    constraint fksp7ty25kndaxyfrgkrloo1dd8
      references author
);

用于导入的 sql 查询示例:

INSERT INTO "public"."books" ("book_id", "author_id") VALUES (1,  2);

通过flyway序列的数据迁移后未更新。那些。我应该有超过 200 个对象,并且序列索引显示 1。

SELECT last_value FROM books_book_id_seq;
last_value 0

在这种情况下,例如,对于由 java 脚本初始化的另一个实体,索引会正确显示。问题与此类似: 链接

如果 GenerationType.IDENTITY ,为什么休眠会生成序列?我的错误是什么?

更新

尝试了其他方法 - 更改了 GenerationType.SEQUENCE hibernate created hibernate_sequence 但也将表 DDL 更改为(bigserial -> bigint):

create table if not exists books
(
  book_id bigint not null
    constraint books_pkey
      primary key,
  language_id bigint
    constraint fksp7ty25kndaxyfrgkrloo1dd8
      references author
);

在任何情况下,当通过 flyway 迁移时,该值都不会增加。我可以手动更正此值的最大值。

好吧,既然序列中的值不正确,那么这里就是异常——DataIntegrityViolationException

提前感谢您的回复!

spring
  • 1 个回答
  • 10 Views
Martin Hope
Orkhan Hasanli
Asked: 2020-04-01 10:40:53 +0000 UTC

Spring 如何在百里香模板中输出值?

  • 0

情况是这样的——我把它List<String> skills从用户配置文件放在前面。有必要显示这个列表,用逗号分隔作为输入字段的值。

尝试了以下 -

<input id="skills" type="text" class="form-control" name="skills[]" th:value="${#strings.listJoin(#messages.listMsg(currentUser.profile.skills), ',')}" />

问题 -

<input id="skills" type="text" class="form-control" name="skills[]" value="??Java_ru??,??PHP_ru??,??JavaScript_ru??">

请注意,??*_ru??发生这种情况是因为我配置了国际化并且 Spring 正在尝试查找具有此类本地化的字符串。

另一个输出选项:

<input id="skills" type="text" class="form-control" name="skills[]" th:each="skill, iterStat : ${currentUser.profile.skills}" th:value="!${iterStat.last} ? ${skill} + ',': ${skill}" />

在这种情况下,它的输出如下:

<input id="skills" type="text" class="form-control" name="skills[]" value="Java,">

由于某种原因,它只显示一个标签,而不是 3 个。

有什么问题?在此先感谢您的帮助!

spring
  • 1 个回答
  • 10 Views
Martin Hope
Orkhan Hasanli
Asked: 2020-01-14 10:31:59 +0000 UTC

为什么会出现 Illegalstateexception getoutputstream() 错误?

  • 1

我使用 @Projection 将 JSON 返回到 RestController。在这里,实体本身

@Entity
@Data
@Table(name = "translations")
public class Translation {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long translationId;

    @Column
    private String locale;

    @Lob
    @Column(name = "messagekey", length = 3000)
    private String key;

    @Lob
    @Column(name = "messagecontent", length = 100000)
    private String content;

    public Translation() {}

}

这是该实体的投影:

public interface TranslationProjection {

    @JsonIgnore
    String getMessagekey();

    Long getId_Ru();

    Long getId_En();

    @JsonIgnore
    String getContent_Ru();

    @JsonIgnore
    String getContent_En();
}

这是存储库中返回投影的方法:

@Repository
public interface TranslationRepository extends JpaRepository<Translation, Long> {

@Query(value =
        "SELECT \"messagekey\", " +
                "MAX(CASE WHEN (\"locale\"='ru') THEN \"messagecontent\" ELSE null END ) AS content_ru, " +
                "MAX(CASE WHEN (\"locale\"='en') THEN \"messagecontent\" ELSE null END ) AS content_en, " +
                "MAX(CASE WHEN (\"locale\"='ru') THEN \"translation_id\" ELSE null END ) AS id_ru, " +
                "MAX(CASE WHEN (\"locale\"='en') THEN \"translation_id\" ELSE null END ) AS id_en " +
                "FROM \"translations\" GROUP BY \"messagekey\";", nativeQuery = true)
List<TranslationProjection> getAllTranslationsWithLocaleAndId();

}

SQL 查询本身不包含错误,并在控制台中正确执行。

SQL查询(MySQL,H2)

SELECT "messagekey",
       MAX(CASE WHEN ("locale"='ru') THEN "messagecontent" ELSE null END ) AS content_ru,
       MAX(CASE WHEN ("locale"='en') THEN "messagecontent" ELSE null END ) AS content_en,
       MAX(CASE WHEN ("locale"='ru') THEN "translation_id" ELSE null END ) AS id_ru,
       MAX(CASE WHEN ("locale"='en') THEN "translation_id" ELSE null END ) AS id_en
FROM "translations" GROUP BY "messagekey";

结果(屏幕): 在此处输入图像描述

问题 - 访问控制器时,出现异常:

@RestController
@RequestMapping("/admin/ajax/translations")
public class BackendAjaxTranslationController {

    @Autowired
    private TranslationRepository translationRepository;

    @GetMapping
    public List<TranslationProjection> getAllTranslations() {
        return translationRepository.getAllTranslationsWithLocaleAndId();
    }
}

异常 - java.lang.IllegalStateException: getOutputStream() 已为此响应调用

    java.lang.IllegalStateException: getOutputStream() has already been called for this response
        at org.apache.catalina.connector.Response.getWriter(Response.java:581) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:227) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:114) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:114) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at org.springframework.security.web.util.OnCommittedResponseWrapper.getWriter(OnCommittedResponseWrapper.java:155) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:114) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at org.springframework.security.web.util.OnCommittedResponseWrapper.getWriter(OnCommittedResponseWrapper.java:155) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:360) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
        at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:189) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.27.jar:9.0.27]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.j

ava:126) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:158) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1579) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

为避免此异常,TranslationProjection 将 @JsonIgnore 注释添加到投影字符串值。如果字符串值没有这个注解就会出错,如果忽略这些String值,那么就没有错误。

结果:

[{"id_Ru":687,"id_En":688},{"id_Ru":943,"id_En":944}]

我知道这通常是使用@OneToMany 和@ManyToOne 时的问题。但在这种情况下,实体本身和它的投影都不是指对象。可能是什么问题呢?我还尝试在 SQL 中设置 LIMIT 10,但仍然没有帮助...

我很乐意提供建议和专业帮助)提前谢谢您!

更新! 正如我所建议的那样,我尝试在没有 thymeleaf 模板引擎的情况下在一个干净的项目上运行相同的代码。情况是一样的,虽然异常日志不同。它显示的是 Long 类型的值,但不想显示 String 类型的值。

org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Projection type must be an interface!; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Projection type must be an interface! (through reference chain: java.util.ArrayList[0]->com.sun.proxy.$Proxy113["content_Az"])
    org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:296)
    org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:295)
    org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:181)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:124)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:141)
    org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:82)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
spring
  • 1 个回答
  • 10 Views
Martin Hope
Orkhan Hasanli
Asked: 2020-01-12 06:44:52 +0000 UTC

Spring/Hibernate 中的国际化和本地化

  • 3

再会!

在 Spring Boot 中开发网站时,我想知道是否能胜任国际化。

我重新阅读了许多来自不同服务的不同解决方案,但没有找到满意的答案。

最好学习“最佳实践”并听取您关于实施的想法。对将消息存储在数据库中而不是将它们存储在 messages.properties 文件中的国际化感兴趣

关于我现在如何实现它:基于这篇文章 - https://medium.com/i18n-and-l10n-resources-for-developers/database-stored-messages-for-i18n-in-spring-boot -11dc2ee5c1f7

明显的优点:

  • 数据以一对语言环境、键、内容存储在数据库中的一个表中。使用密钥和本地化,我们找到翻译并将其发送到前面。

缺点:

  • 每个消息本地化组都需要自己独特的。键(我使用UUID.randomUUID())。那些。Locale - ru Locale - en 他们有一个独特的。钥匙。例如主页标题
  • 另一个问题是实体将必要的原语(例如,String)存储在实体本身中是没有意义的,但它们需要存储在转换表中。例如,对于 Page 实体,标题字符串变得不必要,因为该字符串的翻译包含在另一个表中。

这就提出了一个问题——如何正确地将翻译表(实体)与其他实体联系起来,这样就可以通过引用实体本身而不是翻译的本质来获得所需的翻译?

找到了一些解决方案:

  1. https://stackoverflow.com/questions/39704729/how-to-internationalize-a-hibernate-entity 在这里,在第一个选项中,建议存储 HashMap 而不是实体的原语。第二个答案建议链接 ManyToMany 表
  2. https://stackoverflow.com/questions/49916912/most-elegant-solution-for-internationalization-with-jpa-hibernate
  3. https://stackoverflow.com/questions/6350415/internationalization-with-hibernate
  4. https://stackoverflow.com/questions/49916912/most-elegant-solution-for-internationalization-with-jpa-hibernate 在这个选项中,建议为每个实体创建一个翻译表,这也不好。
  5. https://thoughts-on-java.org/localized-data-hibernate/ 还建议为每个实体创建一个单独的表
  6. https://github.com/deathman92/localized 我还发现了这样一个库(尽管它不起作用),借助它您可以使用本地化注释。

真的没有“现成的”解决方案或任何有效解决方案的选项吗?

提前感谢您的建议和回答!

spring
  • 2 个回答
  • 10 Views
Martin Hope
Orkhan Hasanli
Asked: 2020-01-04 04:43:48 +0000 UTC

如何在 Spring Boot 中正确结合 OAuth 授权和常规授权?

  • 1

我正在使用以下配置通过 oauth 和常规授权来实现授权。

@Override
protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests().mvcMatchers("/robots.txt").permitAll()
                    .antMatchers(
                            "/", "/auth", "/signup", "/restore", "/activation/**",
                            "/admin/login", "/admin_restore",
                            "/agreement", "/privacy", "/about-us", "/faq", "/contact-us",
                            "/error",
                            "/page/**", "/categories", "/categories/**"
                    ).permitAll()
                    .anyRequest().authenticated()

                    .and()
                        .formLogin()
                        .loginPage("/auth")
                        .loginProcessingUrl("/auth")
                        .usernameParameter("email")
                        .passwordParameter("password")
                        .defaultSuccessUrl("/")
                        .failureUrl("/auth?authError")
                        .permitAll()

                    .and()
                        .rememberMe()
                        .rememberMeParameter("remember-me")
                        .tokenValiditySeconds(86400)

                    .and()
                        .logout()
                        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                        .logoutSuccessUrl("/")
                        .deleteCookies("JSESSIONID")

                    .and()
                        .oauth2Login().defaultSuccessUrl("/oauth")

                    .and()
                        .exceptionHandling()
                        .accessDeniedPage("/403")

                    .and()
                        .csrf()

                    .and()
                        .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)

                    .and()
                        .headers().frameOptions().sameOrigin();
        }

原则上,授权可以正常工作。但!我还需要在授权用户时确定他的授权日期和时间。我已经实现了常规授权的工作功能,但是 OAuth2 授权存在问题。

@Service
public class UserService implements
        ApplicationListener<AuthenticationSuccessEvent> {

/** 
Переопределяем метод onApplicationEvent(), чтобы при авторизации юзера зафиксировать дату и время его авторизации
   */
  @Override
  public void onApplicationEvent(AuthenticationSuccessEvent event) {
    >>> Ex.here!  String userEmail = ((UserDetails) event.getAuthentication().
            getPrincipal()).getUsername();
    User user = this.userRepository.findByUserEmail(userEmail);
    user.setLastAuthDate(LocalDateTime.now());
    userRepository.save(user);
  }
...
}

如果通过oauth登录,则会出现以下异常:

java.lang.ClassCastException: org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser cannot be cast to org.springframework.security.core.userdetails.UserDetails

因此,问题是 - 如何消除此异常,以便 oauth 用户在进入站点时的授权也是固定的?如何区分普通用户和 oauth 授权用户?我有一个问题......

预先感谢您的帮助!

spring
  • 1 个回答
  • 10 Views
Martin Hope
Orkhan Hasanli
Asked: 2020-12-31 11:02:00 +0000 UTC

在 Spring Boot 中设置多语言时出现 NPE 的原因可能是什么?

  • 0

我使用 Spring Boot + Spring Security。为了实现多语言,我使用这个解决方案 - https://medium.com/i18n-and-l10n-resources-for-developers/database-stored-messages-for-i18n-in-spring-boot-11dc2ee5c1f7

问题是:通常情况下,如果 URL 不存在或发生异常,Spring Security 应该优雅地处理它。例如,如果用户的密码不正确,它应该返回一个带有 ?authError 参数的页面。原则上,在按照上述方法设置多语种之前,一切正常。

现在,当 Spring Security 抛出 NPE 而不是错误处理时,我看到了某种冲突

java.lang.NullPointerException: null
at info.md7.freelance.tools.DBMessageSource.resolveCode(DBMessageSource.java:26) ~[classes/:na]
at org.springframework.context.support.AbstractMessageSource.resolveCodeWithoutArguments(AbstractMessageSource.java:368) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.context.support.AbstractMessageSource.getMessageInternal(AbstractMessageSource.java:212) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.context.support.AbstractMessageSource.getMessage(AbstractMessageSource.java:141) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getMessage(AbstractApplicationContext.java:1310) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.context.support.MessageSourceAccessor.getMessage(MessageSourceAccessor.java:87) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:93) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:175) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:195) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:95) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:141) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) [tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1579) [tomcat-embed-core-9.0.27.jar:9.0.27]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.27.jar:9.0.27]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_211]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_211]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.27.jar:9.0.27]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_211]

DBMessageSource 的内容

@Component("messageSource")
public class DBMessageSource extends AbstractMessageSource {

    @Autowired
    private TranslationRepository languageRepository;

    private static final String DEFAULT_LOCALE_CODE = "az";

    @Override
    protected MessageFormat resolveCode(String key, Locale locale) {
        Translation message = languageRepository.findByKeyAndLocale(key, locale.getLanguage());
        if (message == null) {
            message = languageRepository.findByKeyAndLocale(key, DEFAULT_LOCALE_CODE);
        }
        >>> return new MessageFormat(message.getContent(), locale);
    }

}

它是空的

message.getContent()

由于某种原因,AbstractUserDetailsAuthenticationProvider.badCredentials 作为键传递给 resolveCode() 方法,因此会出现 500 错误。

如何消除异常?我不明白腿是从哪里长出来的......

准备好提供对 BitBucket 或 Github 的访问权限。已经是我战斗的第二天)))

提前感谢您的建议和帮助!

PS祝大家新年快乐!

spring
  • 1 个回答
  • 10 Views
Martin Hope
Orkhan Hasanli
Asked: 2020-12-27 21:53:24 +0000 UTC

如何在 Spring Boot 中实现 i18n 和 l10n?

  • 0

简而言之,我已经按照这里描述的传统方式在 Spring Boot 中实现了本地化和国际化: https ://www.baeldung.com/spring-boot-internationalization 简单地说,所有本地化文件都存储在 messages.properties 中,相应地,如有必要,他们从那里得到。但是数据库中存储了一些动态内容,这也需要本地化。不要每次都编辑 messages.properties 文件。我找到了以下实现,当为本地化创建一个单独的实体时,它以键值对的形式存储在数据库中。 https://medium.com/i18n-and-l10n-resources-for-developers/database-stored-messages-for-i18n-in-spring-boot-11dc2ee5c1f7 如果计划将本地化文本存储在实体类的相应表中,情况会怎样?例如,有实体 - 文章。因此,将有列 title_ru content_ru title_en content_en 并相应地在访问时获得必要的翻译......在这种情况下,良好形式的规则是什么?在此先感谢您的帮助!

spring
  • 1 个回答
  • 10 Views
Martin Hope
Orkhan Hasanli
Asked: 2020-03-26 23:37:42 +0000 UTC

如何将值从 .properties 传递到 javascript 文件?

  • 0

有时需要将一些变量从属性传递到 javascript 文件。当js代码内联连接时,那么使用thymeleaf传递想要的变量就没有问题了。如何将特定变量从属性传递到 js 文件?提前致谢!

目前我有2个解决方案:1)创建@ControllerAdvice并添加@ModelAttribute并在方法中返回Map。使用 th:each 将其输出到 thymeleaf。然后,使用脚本,获取所需标签的数据属性。2) 使用 GET 方法创建一个 @RestController,该方法在访问时返回一个 Map。然后脚本向 URL 发出 Ajax 请求并接收必要的参数。

spring
  • 1 个回答
  • 10 Views
Martin Hope
Orkhan Hasanli
Asked: 2020-03-22 03:29:23 +0000 UTC

如何在 Spring 中克服 UnsupportedOperationException: null?

  • 0

我遇到了一个相当奇怪的问题。有一个实体 User 和这个类的对象需要通过多对多的关系相互连接。因此,除了主表“user”之外,还应该出现另外 2 个表“customer_authors”“author_customers”

@Entity
public class User {

  @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    // ID пользователя
    private Long userId;


    // "customer_authors"
    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name = "customer_authors",
            joinColumns = @JoinColumn(name = "customer_id"),
            inverseJoinColumns = @JoinColumn(name = "author_id"))
    private List<User> authorsList = new ArrayList<>();

    // "author_customers"
    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name = "author_customers",
            joinColumns = @JoinColumn(name = "author_id"),
            inverseJoinColumns = @JoinColumn(name = "customer_id"))
    private List<User> customersList = new ArrayList<>();

    // getters, setters and other data.
}

在我的代码中没有任何地方使用数组 asList() / 创建了一个固定大小的列表。确切地说,根据谷歌搜索和stackoverflow,这是类似错误的原因......

就我而言,如果我在 @Service UserService 中使用类似的代码:

user.setUserEmail(userEmail);
user.setUserPassword(passwordEncoder.encode(userPassword));
userRepository.save(user);

User referrer = userRepository.findUserByUserId(referrerId);
referrer.getAuthorsList().add(user);
userRepository.save(referrer);

然后我得到相应的错误 -

UnsupportedOperationException

// excerpt
java.lang.UnsupportedOperationException: null
  at com.sun.proxy.$Proxy142.save(Unknown Source) ~[na:na]
  at info.md7.textpool.services.UserService.addUser(UserService.java:252) ~[classes/:na]
  at info.md7.textpool.controllers.UserController.userRegistration(UserController.java:54) ~[classes/:na]

但同时,如果你在控制器中使用这样的东西进行测试:

User customer = (User) userService.findUserByEmail(currentUser.getUsername());
    User author = userRepository.findByUserEmail("sukkivulmo@desoz.com");
    customer.getAuthorsList().add(author);
    userRepository.save(author);

然后确实将引用者 ID 和用户 ID 的必要信息添加到表中。

可能是什么错误?也许有人经历过这个并且知道如何解决它?先感谢您!

来自 UserService 的完整方法片段:

public boolean addUser(  //todo добавить тип работы
          String userFullname,
          String userEmail,
          String userPassword,
          String prefLangs,
          String prefCats,
          Double paymentCost,
          String paymentMethod,
          String paymentWallet,
          Long referrerId,
          User user
  ) throws MessagingException {

    User userFromDbEmail = userRepository.findByUserEmail(userEmail);
    User referrer = userRepository.findUserByUserId(referrerId);

    if(userFromDbEmail != null) {
      return false;
    }

    /*
     * Проверяем наличие данных в полях prefLang, prefCats, paymentCost, paymentMethod, paymentWallet.
     * И если они имеются в одном из полей, то регистрируем пользователя, как Автора.
     * В противном случае, создаем нового Заказчика.
     *
     */

    if(
        prefLangs != null && !prefLangs.isEmpty() ||
        prefCats != null && !prefCats.isEmpty() ||
        paymentCost != null ||
        paymentMethod != null && !paymentMethod.isEmpty() ||
        paymentWallet != null && !paymentWallet.isEmpty()
    ) {

      user.setUserFullname(userFullname);
      user.setUserEmail(userEmail);
      user.setUserPassword(passwordEncoder.encode(userPassword));
      user.setRegDate(LocalDateTime.now());
      user.setUserActive(false);
      user.setRoles(Collections.singleton(Role.AUTHOR));
      user.setActivationCode(UUID.randomUUID().toString());
      user.setUserMode("author");
      user.setReceiveEmails(true);

      // Если пользователь был приглашен, то находим реферрера и добавлем в его список нового пользователя
      User referrer = userRepository.findUserByUserId(referrerId);
      user.setReferrerId(referrer);

      userRepository.save(user);


      /*  Добавляем метаданные для юзера
          С связи с особенностями верстки, данные скриптом вставляю в hidden input поле, после чего
          получаю String разделенный запятыми и разобрав добавляю данные в user_meta
       */
      assert prefLangs != null;
      String[] prefLang = prefLangs.split(",");
      for (String metaValue : prefLang) {
        UserMeta userMeta = new UserMeta();
        String metaKey = "prefLang";
        userMeta.setMetaKey(metaKey);
        userMeta.setMetaValue(metaValue);
        userMeta.setUser(user);
        userMetaRepository.save(userMeta);
      }

      assert prefCats != null;
      String[] prefCat = prefCats.split(",");
      for (String metaValue : prefCat) {
        UserMeta userMeta = new UserMeta();
        String metaKey = "prefCat";
        userMeta.setMetaKey(metaKey);
        userMeta.setMetaValue(metaValue);
        userMeta.setUser(user);
        userMetaRepository.save(userMeta);
      }

      UserMeta paymentMeta = new UserMeta();
      paymentMeta.setMetaKey(paymentMethod);
      paymentMeta.setMetaValue(paymentWallet);
      paymentMeta.setUser(user);
      userMetaRepository.save(paymentMeta);

      if(paymentCost != null) {
        UserMeta paymentCostMeta = new UserMeta();
        paymentCostMeta.setMetaKey("paymentCost");
        paymentCostMeta.setMetaValue(paymentCost.toString());
        paymentCostMeta.setUser(user);
        userMetaRepository.save(paymentCostMeta);
      }


      referrer.getAuthorsList().add(user);
      userRepository.save(referrer);

    } else {

      user.setUserFullname(userFullname);
      user.setUserEmail(userEmail);
      user.setUserPassword(passwordEncoder.encode(userPassword));
      user.setRegDate(LocalDateTime.now());
      user.setUserActive(false);
      user.setRoles(Collections.singleton(Role.CUSTOMER));
      user.setActivationCode(UUID.randomUUID().toString());
      user.setUserMode("customer");
      user.setReceiveEmails(true);

      // Если пользователь был приглашен, то находим реферрера и добавлем в его список нового пользователя
      User referrer = userRepository.findUserByUserId(referrerId);
      user.setReferrerId(referrer);

      userRepository.save(user);


      referrer.getCustomersList().add(user);
      userRepository.save(referrer);

    }

    return true;
  }
java
  • 2 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5