小编Nuñ*_*ada的帖子

SpringBoot 2.0.4 中同一实体的多种表示

我有一个基本的 SpringBoot 2.0.4.RELEASE 应用程序。使用 Spring Initializer、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR 文件。

我有一个具有角色的用户对象:

@Entity
@Table(name="t_user")
public class User implements Serializable, UserDetails {


 @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
    @JoinTable(
        name="t_user_role",
        joinColumns=@JoinColumn(name="user_id", referencedColumnName="id"),
        inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="id"))
    private Set<Role> roles = new HashSet<>();
..
}
Run Code Online (Sandbox Code Playgroud)

当我启动应用程序时。我创建了所有角色:

roleService.save(new Role(RolesEnum.USER.getRoleName()));
roleService.save(new Role(RolesEnum.ADMIN.getRoleName()));
Run Code Online (Sandbox Code Playgroud)

然后我创建一个具有 USER 角色的用户:

User user1 = new User();


         Role role = roleService.findByName(RolesEnum.USER.getRoleName());

         user.getRoles().add(role);
          userService.save(user);
Run Code Online (Sandbox Code Playgroud)

但是当我创建另一个具有相同角色的用户时:

User user2 = new User();


         Role role = roleService.findByName(RolesEnum.USER.getRoleName());

         user2.getRoles().add(role);
          user2Service.save(user);
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

Multiple representations of the same entity [com.tdk.backend.persistence.domain.backend.Role#1] are …
Run Code Online (Sandbox Code Playgroud)

hibernate spring-mvc spring-data spring-data-jpa spring-boot

5
推荐指数
1
解决办法
7567
查看次数

更改Stream的map函数中字段的值

我想改变一个字段的值Stream.我试图改变它,.map但我得到了一个编译错误

令牌上的语法错误,错放的构造(s)

流:

user.getMenuAlertNotifications()
    .parallelStream()
    .filter(not -> not.getUser().getId()==userId &&
                   notificationList.getIds().contains(not.getId()))
    .map(not -> not.setRead(Boolean.TRUE) -> not)
    .forEach(not -> menuService.save(not));
Run Code Online (Sandbox Code Playgroud)

java functional-programming java-8 java-stream

5
推荐指数
1
解决办法
161
查看次数

Java 8 compute()和computeIfPresent()来检查现有值

我有这段代码:

if (notificationSend.get(key) != null && notificationSend.get(key).equals(value)) {
   return true;
} else {
   notificationSend.put(key, value);
   return false;
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有可能使用Jav8增强功能重构它compute(),computeIfPresent()或者computeIfAbsent()

java collections hashmap java-8

5
推荐指数
1
解决办法
359
查看次数

在AWS中使用liquibase更新MySQL 5.6.40 DD

我刚在AWS中创建了一个DB MySQL 5.6.40.我可以使用Sequel Pro 1.1.2连接到数据库

这是我在pom.xml文件中的配置:

<plugin>
  <groupId>org.liquibase</groupId>
  <artifactId>liquibase-maven-plugin</artifactId>
  <version>3.5.3</version>
  <configuration>
    <changeLogFile>src/main/resources/datamodel/liquibaseChangeLog.xml</changeLogFile>
    <driver>com.mysql.jdbc.Driver</driver>
    <url>pradera.cwob2oxhu1so.eu-central-1.rds.amazonaws.com</url>
    <username>pradera</username>
    <password>AzSWMdlckdstgs0aed</password>
  </configuration>
  <executions>
    <execution>
      <phase>process-resources</phase>
      <goals>
        <goal>updateSQL</goal>
      </goals>
    </execution>
  </executions>
  <dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.27</version>
    </dependency>
  </dependencies>
</plugin>
Run Code Online (Sandbox Code Playgroud)

但是当我跑 mvn clean package -DskipTests

我收到了这个错误:

错误]无法执行目标org.liquibase:liquibase-maven-plugin:3.5.3:updateSQL(默认)项目icrypts:设置或运行Liquibase时出错:liquibase.exception.DatabaseException:liquibase.exception.DatabaseException:Connection not not not使用驱动程序com.mysql.jdbc.Driver创建pradera.cwob2oxhu1so.eu-central-1.rds.amazonaws.com.可能是给定数据库URL的错误驱动程序 - > [帮助1] [错误]

mysql liquibase amazon-web-services amazon-rds spring-boot

5
推荐指数
1
解决办法
113
查看次数

java.lang.NoSuchMethodError:org.json.JSONObject。&lt;init&gt;(Ljava / lang / Object;)V

我有一个基本的SpringBoot 2.1.5.RELEASE应用程序。使用Spring Initializer,JPA,嵌入式Tomcat,Thymeleaf模板引擎,并将其打包为带有某些RestController的可执行JAR文件。

在控制器的1中,这是我发送的正文:

{
    "depositHotel": "xxx",
    "destinationHotel": "aaa",
    "depositHotelAmount": "0.2",
    "destinationHotelAmount": "4",
    "destinationAddress": [{
        "address": "asdf",
        "tag": ""
    }],
    "refundAddress": [{
        "address": "pio",
        "tag": ""
    }]
}
Run Code Online (Sandbox Code Playgroud)

因此,我创建了该类以将其作为RequestBody发送:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"address",
"tag"
})
public class Address {



    public Address() {
        super();
    }

    public Address(String address) {
        super();
        this.address = address;
    }

    @JsonProperty("address")
    private String address;
    @JsonProperty("tag")
    private Object tag;


    @JsonProperty("address")
    public String getAddress() {
    return address;
    }

    @JsonProperty("address")
    public void setAddress(String address) {
    this.address = address;
    }

    @JsonProperty("tag")
    public …
Run Code Online (Sandbox Code Playgroud)

java spring json spring-mvc spring-boot

5
推荐指数
3
解决办法
436
查看次数

在类路径上发现多次出现 org.json.JSONObject:

我有一个基本的 SpringBoot 2.1.5.RELEASE 应用程序。使用 Spring Initializer、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR。当我初始化应用程序时,我看到以下消息:

Found multiple occurrences of org.json.JSONObject on the class path:

        jar:file:/Users/nunito/.m2/repository/com/vaadin/external/google/android-json/0.0.20131108.vaadin1/android-json-0.0.20131108.vaadin1.jar!/org/json/JSONObject.class
        jar:file:/Users/nunito/.m2/repository/org/json/json/20160810/json-20160810.jar!/org/json/JSONObject.class
Run Code Online (Sandbox Code Playgroud)

我已经删除了所有的 repositoy 文件夹并从 scracth 开始,但我仍然有问题,我无法通过查看我的 pom.xml 来弄清楚它是什么时候:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>       

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency> 

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
         </dependency>

         <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.googlecode.libphonenumber</groupId> …
Run Code Online (Sandbox Code Playgroud)

java json spring-boot

5
推荐指数
1
解决办法
4864
查看次数

Maven 将文件上传到没有 groupId 和 artifactId 的 Nexus 存储库

我有一个 zip 文件和一个 Nexus 存储库,我想知道是否可以创建一个目标来将 zip 文件上传到存储库根文件夹中,而没有 groupId 和 artifactId

我的工件是由 pom.xml 构建的

java nexus maven-plugin maven maven-assembly-plugin

5
推荐指数
1
解决办法
293
查看次数

使用 JNDI 配置数据源使用外部 Tomcat 9 服务器:Spring Boot

我有一个 SpringBootApplication,打包为 war 文件:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

}
Run Code Online (Sandbox Code Playgroud)

在 application.properties 上:

spring.datasource.jndi-name=java:comp/env/jdbc/bonanza
Run Code Online (Sandbox Code Playgroud)

但是在日志中,当我在 Tomcat 9 中部署战争时,我看到了这些消息:

Name [spring.datasource.jndi-name] is not bound in this Context. Unable to find [spring.datasource.jndi-name].. Returning null.
Run Code Online (Sandbox Code Playgroud)

日志:

12:37:53.989 [main] DEBUG o.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/spring.datasource.jndi-name]
12:37:53.989 [main] DEBUG o.s.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/spring.datasource.jndi-name] not found - trying …
Run Code Online (Sandbox Code Playgroud)

java jndi spring-mvc spring-boot tomcat9

5
推荐指数
1
解决办法
1510
查看次数

已完成 406 NOT_ACCEPTABLE - 在 SpringBoot 中测试 WebLayer

我在 Spring Boot v2.1.0.RELEASE 应用程序中有这个方法。

@GetMapping(value = "/wildProject", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<WildProject>> getList(HttpServletRequest request,
        HttpServletResponse response)
        throws Exception {

    List<WildProject> list = authorisationService.getList();

    System.out.println("-----------------");
    System.out.println(list);
    System.out.println("-----------------");

    return ok().body(list);


} 
Run Code Online (Sandbox Code Playgroud)

和这个测试:

 this.mockMvc.perform(get("/wildProject")
  //.accept(MediaType.APPLICATION_JSON_UTF8_VALUE))
  // .andDo(print())
  .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
  .andExpect(status().isOk());
Run Code Online (Sandbox Code Playgroud)

这是测试的结果:

20:03:38.253 [main] DEBUG o.s.w.s.m.m.a.HttpEntityMethodProcessor - Using 'application/json', given [*/*] and supported [application/json]
20:03:38.255 [main] WARN  o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
20:03:38.256 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Completed 406 NOT_ACCEPTABLE

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /wildProject
       Parameters …
Run Code Online (Sandbox Code Playgroud)

java rest spring json spring-boot

5
推荐指数
1
解决办法
192
查看次数

Spring Boot 安全 + JWT

我有一个使用 JSON Web Tokens 的 SpringBoot 2.4.2 应用程序(JWT,有时发音为 /d\xca\x92\xc9\x92t/,与英语单词“jot”[1]相同)是互联网提出的创建标准具有可选签名和/或可选加密的数据,其有效负载包含断言一定数量声明的 JSON。令牌使用私钥或公钥/私钥进行签名。例如,服务器可以生成一个具有“以管理员身份登录”声明的令牌,并将其提供给客户端。然后,客户端可以使用该令牌来证明它是以管理员身份登录的。

\n

这是我的网络安全配置:

\n
@Configuration\n@EnableWebSecurity\n@EnableGlobalMethodSecurity(prePostEnabled = true)\npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {\n\n    private static final String SALT = "fd23451*(_)nof";\n\n    private final JwtAuthenticationEntryPoint unauthorizedHandler;\n    private final JwtTokenUtil jwtTokenUtil;\n    private final UserSecurityService userSecurityService;\n\n    @Value("${jwt.header}")\n    private String tokenHeader;\n\n\n    public ApiWebSecurityConfig(JwtAuthenticationEntryPoint unauthorizedHandler, JwtTokenUtil jwtTokenUtil,\n            UserSecurityService userSecurityService) {\n        this.unauthorizedHandler = unauthorizedHandler;\n        this.jwtTokenUtil = jwtTokenUtil;\n        this.userSecurityService = userSecurityService;\n    }\n\n    @Autowired\n    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {\n        auth\n                .userDetailsService(userSecurityService)\n                .passwordEncoder(passwordEncoder());\n    }\n\n    @Bean\n    public BCryptPasswordEncoder passwordEncoder() {\n        return …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc jwt spring-boot

5
推荐指数
1
解决办法
1888
查看次数