47 Commits

Author SHA1 Message Date
honeymoose 27db0d5540 J2EE,Java EE,Jakarta EE 命名之间的恩恩怨怨 https://www.ossez.com/t/j2ee-java-ee-jakarta-ee/14382 2023-04-20 16:40:09 -04:00
honeymoose edcd08e1b2 Merge remote-tracking branch 'origin/main' into persistence-modules
# Conflicts:
#	persistence-modules/spring-data-redis/README.md
2023-01-19 13:18:38 -05:00
honeymoose 038ce5b547 介绍 Spring Data Redis https://www.ossez.com/t/spring-data-redis/14299 2023-01-19 13:17:11 -05:00
honeymoose b9d1b0257c redis 测试类进行测试 2023-01-17 14:20:17 -05:00
honeymoose ddbb638242 添加文章:- [解决在 Spring Boot 中运行 JUnit 测试遇到的 NoSuchMethodError 错误](https://www.ossez.com/t/spring-boot-junit-nosuchmethoderror/14066) 2023-01-17 14:20:17 -05:00
honeymoose bf2335eda1 更新 Java 核心的内容 2023-01-17 14:20:17 -05:00
honeymoose 1b3b30cae3 redis 测试类进行测试 2023-01-17 14:18:04 -05:00
honeymoose 4711c3a393 添加文章:- [解决在 Spring Boot 中运行 JUnit 测试遇到的 NoSuchMethodError 错误](https://www.ossez.com/t/spring-boot-junit-nosuchmethoderror/14066) 2022-08-24 15:29:59 -04:00
honeymoose 05d80c840d Merge remote-tracking branch 'origin/main' into persistence-modules 2022-08-24 14:24:01 -04:00
YuCheng Hu 77c51720e9 add test for Spring Boot 2022-08-24 14:08:53 -04:00
honeymoose dc99d9404d 更新 Java 核心的内容 2022-08-22 21:17:14 -04:00
honeymoose 2b1d680b2c 更新 README 文件 2022-08-12 13:30:20 -04:00
honeymoose 3b344e5c9f Merge pull request 'Java 多行字符串' (#45) from persistence-modules into main
Reviewed-on: https://src.ossez.com/cwiki-us-docs/java-tutorials/pulls/45
2022-08-08 09:42:32 -04:00
honeymoose f2c3c2bf0f Java 多行字符串 2022-08-08 09:36:36 -04:00
honeymoose b90cdd3306 讨论字符串的的文章 2022-08-08 09:34:55 -04:00
honeymoose c816787e06 添加核心 Java 的模块,在这里我们主要针对一些环境和 IDE 以及非常基本的问题进行讨论 2022-08-08 09:34:25 -04:00
honeymoose e8f74069ff Java “constant string too long” 编译错误 2022-08-06 10:16:50 -04:00
honeymoose ae29615530 更新 Guava 项目的依赖和 Spring JPA 2022-07-15 14:31:15 -04:00
honeymoose cd46aea7ac Merge pull request 'core-java-strings 字符串压缩 Compact' (#43) from core-java-strings into main
Reviewed-on: https://src.ossez.com/cwiki-us-docs/java-tutorials/pulls/43
2022-07-05 10:21:14 -04:00
honeymoose c6df8af1e0 测试 JDK 9 的字符串压缩 2022-07-05 10:15:52 -04:00
honeymoose b9bf30f350 - [Java 9 中的字符串(String)压缩](https://www.ossez.com/t/java-9-string/14024) 2022-07-05 10:14:24 -04:00
honeymoose 08abc1855a - [Java 9 中的字符串(String)压缩](https://www.ossez.com/t/java-9-string/14024) 2022-07-02 09:27:40 -04:00
honeymoose 25cff75966 更新有关 Java 注解的文章 2022-07-01 17:48:25 -04:00
honeymoose c56e58379a https://www.ossez.com/t/topic/14022 编程常用的几种字符编码 2022-07-01 16:59:57 -04:00
honeymoose 0803488d88 更新 Java String 有关的文章链接 2022-06-29 19:56:57 -04:00
honeymoose b7d0d45f28 添加 Java 中的 String Pool 简介 内容 2022-06-20 17:26:15 -04:00
honeymoose de42646567 格式化输入和输出 2022-06-20 10:46:59 -04:00
honeymoose 61bb6834e6 更新文章 Java 使用 char[] Array 还是 String 存储字符串 的链接 https://www.ossez.com/t/java-char-array-string/14015 2022-06-20 01:09:08 -04:00
honeymoose ed00ae8a6b 添加理解 Java 中的 NumberFormatException 异常 的链接 2022-06-20 01:07:33 -04:00
honeymoose ad2ca48135 更新测试文件注释和文章的内容链接 2022-06-20 01:07:12 -04:00
honeymoose ed4af4389d 添加理解 Java 中的 NumberFormatException 异常 的链接 2022-06-20 01:05:35 -04:00
honeymoose 85b63c6f8d 修改数字格式化异常的内容 2022-06-20 01:03:51 -04:00
honeymoose f08da063e7 尝试触发下 CI 的编译 2022-06-19 09:33:57 -04:00
honeymoose 5b3ef027b1 Merge pull request 'ci' (#39) from ci into main
Reviewed-on: https://src.ossez.com/cwiki-us-docs/java-tutorials/pulls/39
2022-06-18 07:41:52 -04:00
honeymoose 6926189ba0 修改项目的编译错误 2022-06-17 14:32:41 -04:00
honeymoose abf6ebb6e5 <commons-exec.version>1.3</commons-exec.version> 2022-06-17 14:29:02 -04:00
honeymoose f50cfa7686 尝试推送后触发 CI 构建 2022-06-17 14:23:45 -04:00
honeymoose 5523c5fe67 修改构建错误 2022-06-17 14:16:51 -04:00
honeymoose c63d207c77 修改 install 为 package 进行编译 2022-06-17 13:38:17 -04:00
honeymoose 173bb5ef7d 更新 POM.xml 文件能够让构建顺利进行 2022-06-17 13:06:51 -04:00
honeymoose f2200288e7 maven 3.8.4 2022-06-17 12:53:19 -04:00
honeymoose f731671503 WorkflowScript: 5: Tool type "maven" does not have an install of "Maven 3.8.6" configured - did you mean "maven 3.8.4"? @ line 5, column 15.
maven 'Maven 3.8.6'
                 ^

WorkflowScript: 6: Tool type "jdk" does not have an install of "jdk11" configured - did you mean "OpenJDK-11"? @ line 6, column 13.
           jdk 'jdk11'
               ^
2022-06-17 12:52:08 -04:00
honeymoose be05ebb0d3 add tools for Jenkinsfile 2022-06-17 12:51:11 -04:00
honeymoose f0cf866d20 Add steps for mvn build 2022-06-17 12:44:29 -04:00
honeymoose 3c9061cc47 Merge remote-tracking branch 'origin/main' into ci 2022-06-17 12:36:12 -04:00
honeymoose a709139646 添加 Jenkins 的构建文件 2022-06-17 10:47:43 -04:00
honeymoose d66dad8fae 更新错误的 README.md 文件排版格式 2022-06-14 18:14:27 -04:00
168 changed files with 4491 additions and 192 deletions
+46
View File
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="codebank" />
<module name="core-java-collections-list" />
<module name="spring-data-jpa-repo-2" />
<module name="core-java-streams" />
<module name="assertion-libraries" />
<module name="core-java-io" />
<module name="core-java-annotations" />
<module name="core-java-8-2" />
<module name="core-java-numbers" />
<module name="discourse" />
<module name="spring-data-redis" />
<module name="core-java-strings" />
<module name="core-java" />
<module name="core-java-11" />
<module name="core-java-collections-list-2" />
<module name="core-java-collections" />
<module name="core-java-datetime-conversion" />
<module name="core-java-collections-list-3" />
<module name="core-java-8" />
<module name="junit-5-basics" />
<module name="core-java-collections-3" />
<module name="core-java-collections-2" />
<module name="activejdbc" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="core-java-11-2" target="11" />
<module name="hibernate-annotations" target="1.5" />
<module name="hibernate5" target="11" />
</bytecodeTargetLevel>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="core-java-streams" options="-parameters" />
</option>
</component>
</project>
+64
View File
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-11-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-11-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-11/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-11/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-8-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-8-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-8/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-8/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-annotations/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-annotations/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-3/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-3/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-list-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-list-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-list-3/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-list-3/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-datetime-conversion/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-datetime-conversion/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-io/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-io/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-numbers/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-numbers/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-streams/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-streams/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-strings/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-strings/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/activejdbc/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/activejdbc/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/hibernate5/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/hibernate5/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-redis/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-redis/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/testing-modules/assertion-libraries/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/testing-modules/assertion-libraries/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/testing-modules/junit-5-basics/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/testing-modules/junit-5-basics/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/testing-modules/junit-5-basics/src/test/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/testing-modules/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/testing-modules/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/toolkits/codebank/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/toolkits/codebank/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/toolkits/discourse/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/toolkits/discourse/src/main/resources" charset="UTF-8" />
</component>
</project>
+40
View File
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="ossez-repo-snapshots" />
<option name="name" value="OSSEZ Private Snapshots" />
<option name="url" value="https://repo.ossez.com/repository/maven-snapshots/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="geodb-repo" />
<option name="name" value="GeoDB repository" />
<option name="url" value="http://repo.boundlessgeo.com/main/" />
</remote-repository>
<remote-repository>
<option name="id" value="ossez-repo-releases" />
<option name="name" value="OSSEZ Private Releases" />
<option name="url" value="https://repo.ossez.com/repository/maven-releases/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.ossez.com/repository/maven-public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JpaBuddyIdeaProjectConfig">
<option name="defaultUnitInitialized" value="true" />
<option name="renamerInitialized" value="true" />
</component>
</project>
Generated
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MessDetectorOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCSFixerOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCodeSnifferOptionsConfiguration">
<option name="transferred" value="true" />
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ThriftCompiler">
<compilers />
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
Vendored
+27
View File
@@ -0,0 +1,27 @@
pipeline {
agent any
tools {
maven 'maven 3.8.4'
jdk 'OpenJDK-11'
}
stages {
stage('Build') {
steps {
echo 'Building..'
sh 'mvn clean package'
}
}
stage('Test') {
steps {
echo 'Testing..'
}
}
stage('Deploy') {
steps {
echo 'Deploying....'
}
}
}
}
+7 -4
View File
@@ -5,7 +5,7 @@
<br>提供 CWIKI.US 项目中使用的代码 <br>提供 CWIKI.US 项目中使用的代码
</p> </p>
所有的 Java 代码使用的是 JDK 11。 Java 代码使用的是 JDK 11。
你可以通过单击下面连接后访问我们网站,并且访问我们提供的最新有关 Java 的开发资料。 你可以通过单击下面连接后访问我们网站,并且访问我们提供的最新有关 Java 的开发资料。
@@ -25,7 +25,9 @@
# 公众平台 # 公众平台
我们建议您通过社区论坛来和我们进行沟通,请关注我们公众平台上的账号 我们建议您通过社区论坛来和我们进行沟通,请关注我们公众平台上的账号
扫描 QR 关注我们的微信公众号和头条号。
## 微信公众号 ## 微信公众号
@@ -33,10 +35,11 @@
## 头条号 ## 头条号
我们也在头条号上创建了我们的公众号,请扫描下面的 QR 关注我们的头条号。
![](https://cdn.ossez.com/img/cwikius/cwikus-qr-toutiao.png) ![](https://cdn.ossez.com/img/cwikius/cwikus-qr-toutiao.png)
## 知乎
请关注我们的知乎:https://www.zhihu.com/people/huyuchengus
## 快速导航 ## 快速导航
在下面的表格中,我们列出了一些比较有用的 CWIKIUS 相关软件开发使用教程的导航,欢迎访问下面的链接获得更多的内容和参与讨论 在下面的表格中,我们列出了一些比较有用的 CWIKIUS 相关软件开发使用教程的导航,欢迎访问下面的链接获得更多的内容和参与讨论
+4 -3
View File
@@ -1,9 +1,10 @@
## Core Java Modules ## Java 核心模块(Core Java
This module contains modules about core Java 本模块中包含有关 Java 核心(Core Java)有关的内容。
## Relevant articles: ## 相关文章
- [J2EEJava EEJakarta EE 命名之间的恩恩怨怨](https://www.ossez.com/t/j2ee-java-ee-jakarta-ee/14382)
- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception) - [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception)
@@ -3,7 +3,6 @@
本模块中包含有关 Java 11 核心新增功能的的一些文章 本模块中包含有关 Java 11 核心新增功能的的一些文章
### 相关文章 ### 相关文章
- [Java 8 开始新增的 Optional 类](https://www.ossez.com/t/java-8-optional/13964)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection) - [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors) - [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features) - [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
+1 -1
View File
@@ -18,7 +18,7 @@
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${version.guava}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mock-server</groupId> <groupId>org.mock-server</groupId>
+1
View File
@@ -14,3 +14,4 @@ This module contains articles about Java 11 core features
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference) - [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
- [Benchmark JDK Collections vs Eclipse Collections](https://www.baeldung.com/jdk-collections-vs-eclipse-collections) - [Benchmark JDK Collections vs Eclipse Collections](https://www.baeldung.com/jdk-collections-vs-eclipse-collections)
- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile) - [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile)
+1 -1
View File
@@ -20,7 +20,7 @@
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${version.guava}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.openjdk.jmh</groupId> <groupId>org.openjdk.jmh</groupId>
+2 -2
View File
@@ -2,12 +2,12 @@
本模块中包含有关 Java 8 核心新增功能特性的一些文章。 本模块中包含有关 Java 8 核心新增功能特性的一些文章。
### 相关文章 ### 相关文章
- [Run a Java Application from the Command Line](https://www.baeldung.com/java-run-jar-with-arguments) - [Run a Java Application from the Command Line](https://www.baeldung.com/java-run-jar-with-arguments)
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit) - [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface) - [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class) - [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid) - [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
- [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors) - [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors)
- [Java 8 开始新增的 Optional 类](https://www.ossez.com/t/java-8-optional/13964)
- [[<-- Java 8 核心(第 1 部分)]](/core-java-modules/core-java-8) - [[<-- Java 8 核心(第 1 部分)]](/core-java-modules/core-java-8)
@@ -1,6 +1,7 @@
========= ## Annotation(注解)
Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。
## Core Java Cookbooks and Examples Java 语言中的类、方法、变量、参数和包等都可以被标注。和 Javadoc 不同,Java 标注可以通过反射获取标注内容。在编译器生成类文件时,标注可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行时可以获取到标注内容 。 当然它也支持自定义 Java 标注。
### 相关的文章: ### 相关的文章:
- [Java @Override Annotation](https://www.baeldung.com/java-override) - [Java @Override Annotation](https://www.baeldung.com/java-override)
@@ -11,7 +11,6 @@
<groupId>com.ossez.core-java-modules</groupId> <groupId>com.ossez.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId> <artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version> <version>0.0.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@@ -34,6 +33,7 @@
<properties> <properties>
<jol-core.version>0.10</jol-core.version> <jol-core.version>0.10</jol-core.version>
<commons-exec.version>1.3</commons-exec.version>
</properties> </properties>
</project> </project>
@@ -1,4 +1,4 @@
package com.ossez.collections.collections.arraylistvsvector; package com.ossez.collections.arraylistvsvector;
import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.Runner;
@@ -1,4 +1,4 @@
package com.ossez.collections.collections.arraylistvsvector; package com.ossez.collections.arraylistvsvector;
public class Employee { public class Employee {
@@ -1,4 +1,4 @@
package com.ossez.collections.collections.arraylistvsvector; package com.ossez.collections.arraylistvsvector;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Iterator; import java.util.Iterator;
@@ -1,4 +1,4 @@
package com.ossez.collections.collections.containsperformance; package com.ossez.collections.containsperformance;
import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.Runner;
@@ -1,4 +1,4 @@
package com.ossez.collections.collections.containsperformance; package com.ossez.collections.containsperformance;
public class Employee { public class Employee {
@@ -1,4 +1,4 @@
package com.ossez.collections.collections.iterators; package com.ossez.collections.iterators;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -1,4 +1,4 @@
package com.ossez.collections.collections.removeallperformance; package com.ossez.collections.removeallperformance;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
@@ -6,7 +6,7 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.ossez.collections.collections.containsperformance.Employee; import com.ossez.collections.containsperformance.Employee;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.BenchmarkMode;
@@ -1,4 +1,4 @@
package com.ossez.collections.collections.sortingcomparison; package com.ossez.collections.sortingcomparison;
import java.util.Arrays; import java.util.Arrays;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -1,8 +1,8 @@
package com.ossez.collections.iterators; package com.ossez.collections.iterators;
import static com.ossez.collections.collections.iterators.Iterators.failFast1; import static com.ossez.collections.iterators.Iterators.failFast1;
import static com.ossez.collections.collections.iterators.Iterators.failFast2; import static com.ossez.collections.iterators.Iterators.failFast2;
import static com.ossez.collections.collections.iterators.Iterators.failSafe1; import static com.ossez.collections.iterators.Iterators.failSafe1;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -29,7 +29,7 @@
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>log4j</groupId>
<artifactId>log4j</artifactId> <artifactId>log4j</artifactId>
<version>${log4j.version}</version> <version>${version.log4j}</version>
</dependency> </dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency> <dependency>
+2 -2
View File
@@ -71,12 +71,12 @@
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>log4j</groupId>
<artifactId>log4j</artifactId> <artifactId>log4j</artifactId>
<version>${log4j.version}</version> <version>${version.log4j}</version>
</dependency> </dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly --> <dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId> <artifactId>log4j-over-slf4j</artifactId>
<version>${slf4j.version}</version> <version>${version.slf4j}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
@@ -1,6 +1,6 @@
## Java 数字(Number ## Java 数字(Number
这个模块中包含有关 Java 数字(Number)有关的文章。 模块中包含有关 Java 数字(Number)有关的文章。
### 相关文章 ### 相关文章
- [理解 Java 中的 NumberFormatException 异常](https://www.ossez.com/t/java-numberformatexception/13986) - [理解 Java 中的 NumberFormatException 异常](https://www.ossez.com/t/java-numberformatexception/13986)
+3 -4
View File
@@ -8,10 +8,9 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>
<groupId>com.ossez</groupId> <groupId>com.ossez.core-java-modules</groupId>
<artifactId>parent-modules</artifactId> <artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version> <version>0.0.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@@ -49,7 +48,7 @@
<properties> <properties>
<icu4j.version>61.1</icu4j.version> <icu4j.version>61.1</icu4j.version>
<maven.compiler.release>15</maven.compiler.release> <maven.compiler.release>11</maven.compiler.release>
</properties> </properties>
</project> </project>
@@ -15,15 +15,13 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* String format to number with NumberFormatException * String format to number with NumberFormatException
* *
* <p><a href="https://www.ossez.com/t/java-numberformatexception/13986">https://www.ossez.com/t/java-numberformatexception/13986</a></p>
*
* @author YuCheng * @author YuCheng
*/ */
@TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestInstance(TestInstance.Lifecycle.PER_METHOD)
public class NumberFormatExceptionTest { public class NumberFormatExceptionTest {
String stringPassword = "password";
char[] charPassword = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
@Test @Test
public void ConstructorNumberFormatException() { public void ConstructorNumberFormatException() {
@@ -45,7 +43,7 @@ public class NumberFormatExceptionTest {
// Integer aIntegerObj = new Integer("one"); // Integer aIntegerObj = new Integer("one");
// Double doubleDecimalObj = new Double("two.2"); // Double doubleDecimalObj = new Double("two.2");
} }
+1 -1
View File
@@ -35,7 +35,7 @@
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>log4j</groupId>
<artifactId>log4j</artifactId> <artifactId>log4j</artifactId>
<version>${log4j.version}</version> <version>${version.log4j}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
@@ -1,16 +1,17 @@
## Java 字符串(Strings ## Java 字符串(Strings
This module contains articles about strings in Java. 本模块中包含有关 Java 字符串(String)有关的文章。
### 相关文章 ### 相关文章
- [Use char[] Array over a String for Manipulating Passwords in Java?](https://www.baeldung.com/java-storing-passwords) - [Java 使用 char[] Array 还是 String 存储字符串密码](https://www.ossez.com/t/java-char-array-string/14015)
- [Compact Strings in Java 9](https://www.baeldung.com/java-9-compact-string) - [Java 9 中的字符串(String)压缩](https://www.ossez.com/t/java-9-string/14024)
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) - [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
- [String Performance Hints](https://www.baeldung.com/java-string-performance) - [String Performance Hints](https://www.baeldung.com/java-string-performance)
- [Java Localization Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) - [Java Localization Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
- [Java Generate Random String](https://www.baeldung.com/java-random-string) - [Java Generate Random String](https://www.baeldung.com/java-random-string)
- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) - [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
- [Java Multi-line String](https://www.baeldung.com/java-multiline-string) - [Java 多行字符串](https://www.ossez.com/t/java/14049)
- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) - [Java 中的 String Pool 简介](https://www.ossez.com/t/java-string-pool/14017)
- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error) - [Java “constant string too long” 编译错误](https://www.ossez.com/t/java-constant-string-too-long/14048)
- [Java 对象如何安全的 toString](https://www.ossez.com/t/java-tostring/14000) - [Java 对象如何安全的 toString](https://www.ossez.com/t/java-tostring/14000)
- [编程常用的几种字符编码](https://www.ossez.com/t/topic/14022)
+3 -4
View File
@@ -8,10 +8,9 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>
<groupId>com.ossez</groupId> <groupId>com.ossez.core-java-modules</groupId>
<artifactId>parent-modules</artifactId> <artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version> <version>0.0.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@@ -49,7 +48,7 @@
<properties> <properties>
<icu4j.version>61.1</icu4j.version> <icu4j.version>61.1</icu4j.version>
<maven.compiler.release>15</maven.compiler.release> <maven.compiler.release>11</maven.compiler.release>
</properties> </properties>
</project> </project>
@@ -5,21 +5,22 @@ import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toList;
/**
* Java 9 String Compact testing
* <p>
* <p><a href="https://www.ossez.com/t/java-9-string/14024">https://www.ossez.com/t/java-9-string/14024</a></p>
*/
public class CompactStringDemo { public class CompactStringDemo {
public static void main(String[] args) { public static void main(String[] args) {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
List strings = IntStream.rangeClosed(1, 10_000_000) List strings = IntStream.rangeClosed(1, 10_000_000).mapToObj(Integer::toString).collect(toList());
.mapToObj(Integer::toString).collect(toList());
long totalTime = System.currentTimeMillis() - startTime; long totalTime = System.currentTimeMillis() - startTime;
System.out.println("Generated " + strings.size() + " strings in " System.out.println("Generated " + strings.size() + " strings in " + totalTime + " ms.");
+ totalTime + " ms.");
startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis();
String appended = (String) strings.stream().limit(100_000) String appended = (String) strings.stream().limit(100_000).reduce("", (left, right) -> left.toString() + right.toString());
.reduce("", (left, right) -> left.toString() + right.toString());
totalTime = System.currentTimeMillis() - startTime; totalTime = System.currentTimeMillis() - startTime;
System.out.println("Created string of length " + appended.length() System.out.println("Created string of length " + appended.length() + " in " + totalTime + " ms.");
+ " in " + totalTime + " ms.");
} }
} }
@@ -6,13 +6,13 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
public class App { public class App {
/** /**
* Runs all available formatter * Runs all available formatter
* @throws ParseException *
* @param args inputs
*/ */
public static void main(String[] args) { public static void main(String[] args) {
List<Locale> locales = Arrays.asList(new Locale[] { Locale.UK, Locale.ITALY, Locale.FRANCE, Locale.forLanguageTag("pl-PL") }); List<Locale> locales = Arrays.asList(new Locale[]{Locale.UK, Locale.ITALY, Locale.FRANCE, Locale.forLanguageTag("pl-PL")});
Localization.run(locales); Localization.run(locales);
JavaSEFormat.run(locales); JavaSEFormat.run(locales);
ICUFormat.run(locales); ICUFormat.run(locales);
@@ -6,65 +6,108 @@ import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/**
* Java Password by using String or Char array
* <p>
* <p><a href="https://www.ossez.com/t/java-char-array-string/14015">https://www.ossez.com/t/java-char-array-string/14015</a></p>
*/
public class PasswordStoreExamplesUnitTest { public class PasswordStoreExamplesUnitTest {
String stringPassword = "password"; String stringPassword = "password";
char[] charPassword = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; char[] charPassword = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
@Test @Test
public void givenStringHashCode_WhenStringValueChanged_ThenHashCodesNotEqualAndValesNotEqual() { public void givenStringHashCode_WhenStringValueChanged_ThenHashCodesNotEqualAndValesNotEqual() {
String originalHashCode = Integer.toHexString(stringPassword.hashCode()); String originalHashCode = Integer.toHexString(stringPassword.hashCode());
stringPassword = "********"; stringPassword = "********";
String changedHashCode = Integer.toHexString(stringPassword.hashCode()); String changedHashCode = Integer.toHexString(stringPassword.hashCode());
assertThat(originalHashCode).isNotEqualTo(changedHashCode); assertThat(originalHashCode).isNotEqualTo(changedHashCode);
assertThat(stringPassword).isNotEqualTo("password"); assertThat(stringPassword).isNotEqualTo("password");
} }
@Test @Test
public void givenStringHashCode_WhenStringValueChangedAndStringValueReassigned_ThenHashCodesEqualAndValesEqual() { public void givenStringHashCode_WhenStringValueChangedAndStringValueReassigned_ThenHashCodesEqualAndValesEqual() {
String originalHashCode = Integer.toHexString(stringPassword.hashCode()); String originalHashCode = Integer.toHexString(stringPassword.hashCode());
stringPassword = "********"; stringPassword = "********";
stringPassword = "password"; stringPassword = "password";
String reassignedHashCode = Integer.toHexString(stringPassword.hashCode()); String reassignedHashCode = Integer.toHexString(stringPassword.hashCode());
assertThat(originalHashCode).isEqualTo(reassignedHashCode); assertThat(originalHashCode).isEqualTo(reassignedHashCode);
assertThat(stringPassword).isEqualTo("password"); assertThat(stringPassword).isEqualTo("password");
} }
@Test @Test
public void givenStringHashCode_WhenStringValueReplaced_ThenHashCodesEqualAndValesEqual() { public void givenStringHashCode_WhenStringValueReplaced_ThenHashCodesEqualAndValesEqual() {
String originalHashCode = Integer.toHexString(stringPassword.hashCode()); String originalHashCode = Integer.toHexString(stringPassword.hashCode());
String newString = "********"; String newString = "********";
stringPassword.replace(stringPassword, newString); stringPassword.replace(stringPassword, newString);
String hashCodeAfterReplace = Integer.toHexString(stringPassword.hashCode()); String hashCodeAfterReplace = Integer.toHexString(stringPassword.hashCode());
assertThat(originalHashCode).isEqualTo(hashCodeAfterReplace); assertThat(originalHashCode).isEqualTo(hashCodeAfterReplace);
assertThat(stringPassword).isEqualTo("password"); assertThat(stringPassword).isEqualTo("password");
} }
@Test @Test
public void givenCharArrayHashCode_WhenArrayElementsValueChanged_ThenHashCodesEqualAndValesNotEqual() { public void givenCharArrayHashCode_WhenArrayElementsValueChanged_ThenHashCodesEqualAndValesNotEqual() {
String originalHashCode = Integer.toHexString(charPassword.hashCode()); String originalHashCode = Integer.toHexString(charPassword.hashCode());
Arrays.fill(charPassword, '*'); Arrays.fill(charPassword, '*');
String changedHashCode = Integer.toHexString(charPassword.hashCode()); String changedHashCode = Integer.toHexString(charPassword.hashCode());
assertThat(originalHashCode).isEqualTo(changedHashCode); assertThat(originalHashCode).isEqualTo(changedHashCode);
assertThat(charPassword).isNotEqualTo(new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}); assertThat(charPassword).isNotEqualTo(new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'});
} }
@Test @Test
public void whenCallingToStringOfString_ThenValuesEqual() { public void whenCallingToStringOfString_ThenValuesEqual() {
assertThat(stringPassword.toString()).isEqualTo("password"); assertThat(stringPassword.toString()).isEqualTo("password");
} }
@Test @Test
public void whenCallingToStringOfCharArray_ThenValuesNotEqual() { public void whenCallingToStringOfCharArray_ThenValuesNotEqual() {
assertThat(charPassword.toString()).isNotEqualTo("password"); assertThat(charPassword.toString()).isNotEqualTo("password");
} }
@Test
public void immutableForString() {
String stringPassword = "password";
System.out.print("Original String password value: ");
System.out.println(stringPassword);
System.out.println("Original String password hashCode: " + Integer.toHexString(stringPassword.hashCode()));
String newString = "********";
stringPassword.replace(stringPassword, newString);
System.out.print("String password value after trying to replace it: ");
System.out.println(stringPassword);
System.out.println("hashCode after trying to replace the original String: " + Integer.toHexString(stringPassword.hashCode()));
}
@Test
public void immutableForCharArray() {
char[] charPassword = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
System.out.print("Original char password value: ");
System.out.println(charPassword);
System.out.println("Original char password hashCode: " + Integer.toHexString(charPassword.hashCode()));
Arrays.fill(charPassword, '*');
System.out.print("Changed char password value: ");
System.out.println(charPassword);
System.out.println("Changed char password hashCode: " + Integer.toHexString(charPassword.hashCode()));
}
@Test
public void accidentallyPassword_print() {
String passwordString = "password";
char[] passwordArray = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
System.out.println("Printing String password -> " + passwordString);
System.out.println("Printing char[] password -> " + passwordArray.toString());
}
} }
@@ -8,7 +8,7 @@ import static org.junit.Assert.assertEquals;
public class MultiLineStringUnitTest { public class MultiLineStringUnitTest {
@Test @Test
public void whenCompareMultiLineStrings_thenTheyAreAllTheSame() throws IOException { public void whenCompareMultiLineStrings_thenTheyAreAllTheSame() throws IOException {
MultiLineString ms = new MultiLineString(); MultiLineString ms = new MultiLineString();
@@ -16,7 +16,13 @@ public class MultiLineStringUnitTest {
assertEquals(ms.stringJoin(), ms.stringBuilder()); assertEquals(ms.stringJoin(), ms.stringBuilder());
assertEquals(ms.stringBuilder(), ms.guavaJoiner()); assertEquals(ms.stringBuilder(), ms.guavaJoiner());
assertEquals(ms.guavaJoiner(), ms.loadFromFile()); assertEquals(ms.guavaJoiner(), ms.loadFromFile());
assertEquals(ms.loadFromFile(), ms.textBlocks());
// Due to JDK version, we cannot test TestBlocks
// assertEquals(ms.loadFromFile(), ms.textBlocks());
}
@Test
public void newlineInOS() throws IOException {
System.out.println(System.lineSeparator());
System.out.println(System.getProperty("line.separator"));
} }
} }
@@ -3,37 +3,44 @@ package com.ossez.stringpool;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StringPoolUnitTest { public class StringPoolUnitTest {
private static Logger logger = LoggerFactory.getLogger(StringPoolUnitTest.class);
@Test @Test
public void whenCreatingConstantStrings_thenTheirAddressesAreEqual() { public void whenCreatingConstantStrings_thenTheirAddressesAreEqual() {
String constantString1 = "Baeldung"; String constantString1 = "HoneyMoose";
String constantString2 = "Baeldung"; String constantString2 = "HoneyMoose";
assertThat(constantString1).isSameAs(constantString2); assertThat(constantString1).isSameAs(constantString2);
} }
@Test @Test
public void whenCreatingStringsWithTheNewOperator_thenTheirAddressesAreDifferent() { public void whenCreatingStringsWithTheNewOperator_thenTheirAddressesAreDifferent() {
String newString1 = new String("Baeldung"); String newString1 = new String("HoneyMoose");
String newString2 = new String("Baeldung"); String newString2 = new String("HoneyMoose");
assertThat(newString1).isNotSameAs(newString2); assertThat(newString1).isNotSameAs(newString2);
logger.info("newString1 Address: {}", System.identityHashCode(newString1));
logger.info("newString2 Address: {}", System.identityHashCode(newString2));
} }
@Test @Test
public void whenComparingConstantAndNewStrings_thenTheirAddressesAreDifferent() { public void whenComparingConstantAndNewStrings_thenTheirAddressesAreDifferent() {
String constantString = "Baeldung"; String constantString = "HoneyMoose";
String newString = new String("Baeldung"); String newString = new String("HoneyMoose");
assertThat(constantString).isNotSameAs(newString); assertThat(constantString).isNotSameAs(newString);
} }
@Test @Test
public void whenInterningAStringWithIdenticalValueToAnother_thenTheirAddressesAreEqual() { public void whenInterningAStringWithIdenticalValueToAnother_thenTheirAddressesAreEqual() {
String constantString = "interned Baeldung"; String constantString = "interned HoneyMoose";
String newString = new String("interned Baeldung"); String newString = new String("interned HoneyMoose");
assertThat(constantString).isNotSameAs(newString); assertThat(constantString).isNotSameAs(newString);
+26
View File
@@ -0,0 +1,26 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml
+6
View File
@@ -0,0 +1,6 @@
## Java 核心
本模块中包含有关 Java 核心新增功能特性的一些文章。
### 相关文章:
- [Java Preview Features](https://www.baeldung.com/java-preview-features)
+54
View File
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java</artifactId>
<name>core-java</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-8</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- util -->
<commons-collections4.version>4.1</commons-collections4.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
</properties>
</project>
@@ -0,0 +1,11 @@
package com.ossez.features;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
public class Template {
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="TRACE">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,42 @@
package com.ossez.features.util;
import static org.junit.Assert.assertEquals;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import org.junit.jupiter.api.Test;
public class CurrentDateTimeUnitTest {
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
@Test
public void shouldReturnCurrentDate() {
final LocalDate now = LocalDate.now(clock);
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
assertEquals(2016, now.get(ChronoField.YEAR));
}
@Test
public void shouldReturnCurrentTime() {
final LocalTime now = LocalTime.now(clock);
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
}
@Test
public void shouldReturnCurrentTimestamp() {
final Instant now = Instant.now(clock);
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
}
}
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
+2 -1
View File
@@ -15,10 +15,11 @@
</parent> </parent>
<modules> <modules>
<module>core-java</module>
<module>core-java-8</module> <module>core-java-8</module>
<module>core-java-8-2</module> <module>core-java-8-2</module>
<module>core-java-11</module> <module>core-java-11</module>
<module>core-java-11-2</module> <!-- <module>core-java-11-2</module>-->
<module>core-java-annotations</module> <module>core-java-annotations</module>
<module>core-java-collections</module> <module>core-java-collections</module>
<module>core-java-collections-2</module> <module>core-java-collections-2</module>
+2 -2
View File
@@ -5,7 +5,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>parent-boot-2</artifactId> <artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.2-SNAPSHOT</version>
<name>parent-boot-2</name> <name>parent-boot-2</name>
<packaging>pom</packaging> <packaging>pom</packaging>
<description>Parent for all Spring Boot 2 modules</description> <description>Parent for all Spring Boot 2 modules</description>
@@ -13,7 +13,7 @@
<parent> <parent>
<groupId>com.ossez</groupId> <groupId>com.ossez</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<version>0.0.1</version> <version>0.0.2-SNAPSHOT</version>
</parent> </parent>
<dependencyManagement> <dependencyManagement>
+2 -2
View File
@@ -9,9 +9,9 @@
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.ossez</groupId>
<artifactId>persistence-modules</artifactId> <artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>0.0.2-SNAPSHOT</version>
</parent> </parent>
<dependencies> <dependencies>
+2 -2
View File
@@ -8,9 +8,9 @@
<name>hibernate5</name> <name>hibernate5</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.ossez</groupId>
<artifactId>persistence-modules</artifactId> <artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>0.0.2-SNAPSHOT</version>
</parent> </parent>
<dependencies> <dependencies>
+69 -57
View File
@@ -9,70 +9,82 @@
<parent> <parent>
<groupId>com.ossez</groupId> <groupId>com.ossez</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<version>1.0.0</version> <version>0.0.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent> </parent>
<modules> <modules>
<module>activejdbc</module> <module>activejdbc</module>
<module>apache-cayenne</module> <!-- <module>apache-cayenne</module>-->
<module>core-java-persistence</module> <!-- <module>core-java-persistence</module>-->
<module>deltaspike</module> <!-- <module>deltaspike</module>-->
<module>elasticsearch</module> <!-- <module>elasticsearch</module>-->
<module>flyway</module> <!-- <module>flyway</module>-->
<module>hbase</module> <!-- <module>hbase</module>-->
<module>hibernate5</module> <!-- <module>hibernate5</module>-->
<module>hibernate-mapping</module> <!-- long running --> <!-- <module>hibernate-mapping</module> &lt;!&ndash; long running &ndash;&gt;-->
<module>hibernate-ogm</module> <!-- <module>hibernate-ogm</module>-->
<module>hibernate-annotations</module> <!-- <module>hibernate-annotations</module>-->
<module>hibernate-jpa</module> <!-- <module>hibernate-jpa</module>-->
<module>hibernate-queries</module> <!-- <module>hibernate-queries</module>-->
<module>hibernate-enterprise</module> <!-- <module>hibernate-enterprise</module>-->
<module>influxdb</module> <!-- <module>influxdb</module>-->
<module>java-cassandra</module> <!-- <module>java-cassandra</module>-->
<module>java-cockroachdb</module> <!-- <module>java-cockroachdb</module>-->
<module>java-jdbi</module> <!-- <module>java-jdbi</module>-->
<module>java-jpa</module> <!-- long running --> <!-- <module>java-jpa</module> &lt;!&ndash; long running &ndash;&gt;-->
<module>java-jpa-2</module> <!-- long running --> <!-- <module>java-jpa-2</module> &lt;!&ndash; long running &ndash;&gt;-->
<module>java-mongodb</module> <!-- long running --> <!-- <module>java-mongodb</module> &lt;!&ndash; long running &ndash;&gt;-->
<module>jnosql</module> <!-- long running --> <!-- <module>jnosql</module> &lt;!&ndash; long running &ndash;&gt;-->
<module>jpa-hibernate-cascade-type</module> <!-- <module>jpa-hibernate-cascade-type</module>-->
<module>liquibase</module> <!-- <module>liquibase</module>-->
<module>orientdb</module> <!-- <module>orientdb</module>-->
<module>persistence-libraries</module> <!-- <module>persistence-libraries</module>-->
<module>querydsl</module> <!-- <module>querydsl</module>-->
<module>r2dbc</module> <!-- <module>r2dbc</module>-->
<module>redis</module> <!-- <module>redis</module>-->
<!-- <module>sirix</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 --> <!-- <module>sirix</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<module>solr</module> <!-- <module>solr</module>-->
<module>spring-boot-persistence-2</module> <!-- <module>spring-boot-persistence-2</module>-->
<module>spring-boot-mysql</module> <!-- <module>spring-boot-mysql</module>-->
<module>spring-boot-persistence</module> <!-- <module>spring-boot-persistence</module>-->
<module>spring-boot-persistence-h2</module> <!-- <module>spring-boot-persistence-h2</module>-->
<module>spring-boot-persistence-mongodb</module> <!-- <module>spring-boot-persistence-mongodb</module>-->
<module>spring-data-cassandra</module> <!-- <module>spring-boot-persistence-mongodb-2</module>-->
<module>spring-data-cassandra-reactive</module> <!-- <module>spring-data-arangodb</module>-->
<module>spring-data-couchbase-2</module> <!-- <module>spring-data-cassandra</module>-->
<module>spring-data-dynamodb</module> <!-- <module>spring-data-cassandra-test</module>-->
<module>spring-data-eclipselink</module> <!-- <module>spring-data-cassandra-reactive</module>-->
<module>spring-data-elasticsearch</module> <!-- <module>spring-data-cosmosdb</module>-->
<module>spring-data-gemfire</module> <!-- <module>spring-data-couchbase-2</module>-->
<module>spring-data-geode</module> <!-- <module>spring-data-dynamodb</module>-->
<module>spring-data-jpa</module> <!-- <module>spring-data-eclipselink</module>-->
<module>spring-data-jpa-2</module> <!-- <module>spring-data-elasticsearch</module>-->
<module>spring-data-jpa-3</module> <!-- &lt;!&ndash; <module>spring-data-gemfire</module> Fixing in JAVA-11854 &ndash;&gt;-->
<module>spring-data-jpa-4</module> <!-- <module>spring-data-geode</module>-->
<module>spring-data-keyvalue</module> <!-- <module>spring-data-jpa-annotations</module>-->
<module>spring-data-mongodb</module> <!-- <module>spring-data-jpa-crud</module>-->
<module>spring-data-neo4j</module> <!-- <module>spring-data-jpa-crud-2</module>-->
<!-- <module>spring-data-jpa-enterprise</module>-->
<!-- <module>spring-data-jpa-enterprise-2</module>-->
<!-- <module>spring-data-jpa-filtering</module>-->
<!-- <module>spring-data-jpa-query</module>-->
<!-- <module>spring-data-jpa-query-2</module>-->
<!-- <module>spring-data-jpa-query-3</module>-->
<!-- <module>spring-data-jpa-repo</module>-->
<module>spring-data-jpa-repo-2</module>
<!-- <module>spring-data-keyvalue</module>-->
<!-- <module>spring-data-mongodb</module>-->
<!-- <module>spring-data-neo4j</module>-->
<module>spring-data-redis</module> <module>spring-data-redis</module>
<module>spring-data-solr</module> <!-- <module>spring-data-solr</module>-->
<module>spring-hibernate-3</module> <!-- <module>spring-hibernate-3</module>-->
<module>spring-hibernate-5</module> <!-- long running --> <!-- <module>spring-hibernate-5</module> &lt;!&ndash; long running &ndash;&gt;-->
<module>spring-hibernate4</module> <!-- <module>spring-hibernate4</module>-->
<module>spring-jpa</module> <!-- <module>spring-jpa</module>-->
<!-- <module>spring-mybatis</module> --> <!-- needs fixing in BAEL-9021 --> <!-- <module>spring-mybatis</module> --> <!-- needs fixing in BAEL-9021 -->
<module>spring-persistence-simple</module> <!-- <module>spring-persistence-simple</module>-->
<module>spring-persistence-simple-2</module> <!-- <module>spring-persistence-simple-2</module>-->
</modules> </modules>
</project> </project>
@@ -0,0 +1,9 @@
## Spring Data JPA - Repositories
### Relevant Articles:
- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
- [Performance Difference Between save() and saveAll() in Spring Data](https://www.baeldung.com/spring-data-save-saveall)
- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries)
- [How to Access EntityManager with Spring Data](https://www.baeldung.com/spring-data-entitymanager)
- More articles: [[<-- prev]](../spring-data-jpa-repo)
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-data-jpa-repo-2</artifactId>
<name>spring-data-jpa-repo-2</name>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<parent>
<groupId>com.ossez</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${version.guava}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,12 @@
package com.baeldung.spring.data.persistence.customrepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CustomRepositoryApplication {
public static void main(String[] args) {
SpringApplication.run(CustomRepositoryApplication.class, args);
}
}
@@ -0,0 +1,55 @@
package com.baeldung.spring.data.persistence.customrepository.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Objects;
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private String email;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(name, user.name) && Objects.equals(email, user.email);
}
@Override
public int hashCode() {
return Objects.hash(id, name, email);
}
}
@@ -0,0 +1,9 @@
package com.baeldung.spring.data.persistence.customrepository.repository;
import com.baeldung.spring.data.persistence.customrepository.model.User;
public interface CustomUserRepository {
User customFindMethod(Long id);
}
@@ -0,0 +1,26 @@
package com.baeldung.spring.data.persistence.customrepository.repository;
import com.baeldung.spring.data.persistence.customrepository.model.User;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Objects;
public class CustomUserRepositoryImpl implements CustomUserRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public User customFindMethod(Long id) {
return (User) entityManager.createQuery("FROM User u WHERE u.id = :id")
.setParameter("id", id)
.getSingleResult();
}
@PostConstruct
public void postConstruct() {
Objects.requireNonNull(entityManager);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.spring.data.persistence.customrepository.repository;
import com.baeldung.spring.data.persistence.customrepository.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long>, CustomUserRepository {
}
@@ -0,0 +1,13 @@
package com.baeldung.spring.data.persistence.like;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LikeApplication {
public static void main(String[] args) {
SpringApplication.run(LikeApplication.class, args);
}
}
@@ -0,0 +1,58 @@
package com.baeldung.spring.data.persistence.like.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Movie {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String title;
private String director;
private String rating;
private int duration;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
}
@@ -0,0 +1,40 @@
package com.baeldung.spring.data.persistence.like.repository;
import com.baeldung.spring.data.persistence.like.model.Movie;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface MovieRepository extends CrudRepository<Movie, Long> {
List<Movie> findByTitleContaining(String title);
List<Movie> findByTitleLike(String title);
List<Movie> findByTitleContains(String title);
List<Movie> findByTitleIsContaining(String title);
List<Movie> findByRatingStartsWith(String rating);
List<Movie> findByDirectorEndsWith(String director);
List<Movie> findByTitleContainingIgnoreCase(String title);
List<Movie> findByRatingNotContaining(String rating);
List<Movie> findByDirectorNotLike(String director);
@Query("SELECT m FROM Movie m WHERE m.title LIKE %:title%")
List<Movie> searchByTitleLike(@Param("title") String title);
@Query("SELECT m FROM Movie m WHERE m.rating LIKE ?1%")
List<Movie> searchByRatingStartsWith(String rating);
//Escaping works in SpringBoot >= 2.4.1
//@Query("SELECT m FROM Movie m WHERE m.director LIKE %?#{escape([0])} escape ?#{escapeCharacter()}")
@Query("SELECT m FROM Movie m WHERE m.director LIKE %:#{[0]}")
List<Movie> searchByDirectorEndsWith(String director);
}
@@ -0,0 +1,25 @@
package com.baeldung.spring.data.persistence.saveperformance;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String title;
private String author;
public Book(final String title, final String author) {
this.title = title;
this.author = author;
}
public Book() {
}
}
@@ -0,0 +1,52 @@
package com.baeldung.spring.data.persistence.saveperformance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class BookApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(BookApplication.class);
@Autowired
private BookRepository bookRepository;
public static void main(String[] args) {
SpringApplication.run(BookApplication.class, args);
}
@EventListener(ApplicationReadyEvent.class)
public void executePerformanceBenchmark() {
int bookCount = 10000;
long start = System.currentTimeMillis();
for (int i = 0; i < bookCount; i++) {
bookRepository.save(new Book("Book " + i, "Author " + i));
}
long end = System.currentTimeMillis();
bookRepository.deleteAll();
LOGGER.debug("It took {}ms to execute save() for {} books.", (end - start), bookCount);
List<Book> bookList = new ArrayList<>();
for (int i = 0; i < bookCount; i++) {
bookList.add(new Book("Book " + i, "Author " + i));
}
start = System.currentTimeMillis();
bookRepository.saveAll(bookList);
end = System.currentTimeMillis();
LOGGER.debug("It took {}ms to execute saveAll() with {}} books.", (end - start), bookCount);
}
}
@@ -0,0 +1,7 @@
package com.baeldung.spring.data.persistence.saveperformance;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}
@@ -0,0 +1,72 @@
package com.baeldung.spring.data.persistence.saveperformance.repository;
import javax.persistence.*;
import java.io.Serializable;
@Entity
public class Foo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String name;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}
@@ -0,0 +1,15 @@
package com.baeldung.spring.data.persistence.saveperformance.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class FooService implements IFooService {
@Autowired
private IFooDAO dao;
@Override
public Foo create(Foo foo) {
return dao.save(foo);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.spring.data.persistence.saveperformance.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface IFooDAO extends JpaRepository<Foo, Long> {
Foo findByName(String name);
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
Foo retrieveByName(@Param("name") String name);
}
@@ -0,0 +1,5 @@
package com.baeldung.spring.data.persistence.saveperformance.repository;
public interface IFooService {
Foo create(Foo foo);
}
@@ -0,0 +1,81 @@
package com.baeldung.spring.data.persistence.saveperformance.repository;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@PropertySource("classpath:persistence.properties")
@ComponentScan("com.baeldung.spring.data.persistence.repository")
//@ImportResource("classpath*:*springDataConfig.xml")
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.repository")
public class PersistenceConfig {
@Autowired
private Environment env;
public PersistenceConfig() {
super();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.baeldung.spring.data.persistence.repository");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
return hibernateProperties;
}
}
@@ -0,0 +1,3 @@
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,9 @@
# jdbc.X
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.user=sa
jdbc.pass=sa
# hibernate.X
hibernate.hbm2ddl.auto=create-drop
hibernate.dialect=org.hibernate.dialect.H2Dialect
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
>
<jpa:repositories base-package="com.baeldung.spring.data.persistence.repository"/>
</beans>
@@ -0,0 +1,27 @@
package com.baeldung.spring.data.persistence.customrepository;
import com.baeldung.spring.data.persistence.customrepository.model.User;
import com.baeldung.spring.data.persistence.customrepository.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest(classes = CustomRepositoryApplication.class)
class CustomRepositoryUnitTest {
@Autowired
private UserRepository userRepository;
@Test
void givenCustomRepository_whenInvokeCustomFindMethod_thenEntityIsFound() {
User user = new User();
user.setEmail("foo@gmail.com");
user.setName("userName");
User persistedUser = userRepository.save(user);
assertEquals(persistedUser, userRepository.customFindMethod(user.getId()));
}
}
@@ -0,0 +1,91 @@
package com.baeldung.spring.data.persistence.like;
import com.baeldung.spring.data.persistence.like.model.Movie;
import com.baeldung.spring.data.persistence.like.repository.MovieRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
@RunWith(SpringRunner.class)
@Sql(scripts = { "/test-movie-data.sql" })
@SpringBootTest(classes = LikeApplication.class)
@Sql(scripts = "/test-movie-cleanup.sql", executionPhase = AFTER_TEST_METHOD)
public class MovieRepositoryIntegrationTest {
@Autowired
private MovieRepository movieRepository;
@Autowired
private DataSource dataSource;
@Test
public void givenPartialTitle_WhenFindByTitleContaining_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByTitleContaining("in");
assertEquals(3, results.size());
results = movieRepository.findByTitleLike("%in%");
assertEquals(3, results.size());
results = movieRepository.findByTitleIsContaining("in");
assertEquals(3, results.size());
results = movieRepository.findByTitleContains("in");
assertEquals(3, results.size());
}
@Test
public void givenStartOfRating_WhenFindByRatingStartsWith_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByRatingStartsWith("PG");
assertEquals(6, results.size());
}
@Test
public void givenLastName_WhenFindByDirectorEndsWith_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByDirectorEndsWith("Burton");
assertEquals(1, results.size());
}
@Test
public void givenPartialTitle_WhenFindByTitleContainingIgnoreCase_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByTitleContainingIgnoreCase("the");
assertEquals(2, results.size());
}
@Test
public void givenPartialTitle_WhenSearchByTitleLike_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.searchByTitleLike("in");
assertEquals(3, results.size());
}
@Test
public void givenStartOfRating_SearchFindByRatingStartsWith_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.searchByRatingStartsWith("PG");
assertEquals(6, results.size());
}
@Test
public void givenLastName_WhenSearchByDirectorEndsWith_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.searchByDirectorEndsWith("Burton");
assertEquals(1, results.size());
}
@Test
public void givenPartialRating_findByRatingNotContaining_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByRatingNotContaining("PG");
assertEquals(1, results.size());
}
@Test
public void givenPartialDirector_WhenFindByDirectorNotLike_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByDirectorNotLike("An%");
assertEquals(5, results.size());
}
}
@@ -0,0 +1,29 @@
package com.baeldung.spring.data.persistence.repository;
import com.baeldung.spring.data.persistence.saveperformance.repository.Foo;
import com.baeldung.spring.data.persistence.saveperformance.repository.IFooService;
import com.baeldung.spring.data.persistence.saveperformance.repository.PersistenceConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = PersistenceConfig.class)
public class FooServiceIntegrationTest {
@Autowired
private IFooService service;
@Autowired
private DataSource dataSource;
@Test(expected = DataIntegrityViolationException.class)
public final void whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo());
}
}
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1 @@
DELETE FROM Movie;
@@ -0,0 +1,7 @@
INSERT INTO movie(id, title, director, rating, duration) VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132);
INSERT INTO movie(id, title, director, rating, duration) VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181);
INSERT INTO movie(id, title, director, rating, duration) VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123);
INSERT INTO movie(id, title, director, rating, duration) VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112);
INSERT INTO movie(id, title, director, rating, duration) VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102);
INSERT INTO movie(id, title, director, rating, duration) VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128);
INSERT INTO movie(id, title, director, rating, duration) VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100);
@@ -0,0 +1,16 @@
## Spring Data Redis
### 相关文章:
- [介绍 Spring Data Redis](https://www.ossez.com/t/spring-data-redis/14299)
- [PubSub Messaging with Spring Data Redis](https://www.baeldung.com/spring-data-redis-pub-sub)
- [An Introduction to Spring Data Redis Reactive](https://www.baeldung.com/spring-data-redis-reactive)
### 构建项目并且运行所有的测试
```
mvn clean install
```
### 只运行测试
```
mvn test
```
@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-data-redis</artifactId>
<version>1.0</version>
<name>spring-data-redis</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.lordofthejars</groupId>
<artifactId>nosqlunit-redis</artifactId>
<version>${nosqlunit.version}</version>
</dependency>
<dependency>
<groupId>com.github.kstyrc</groupId>
<artifactId>embedded-redis</artifactId>
<version>${embedded-redis.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<verbose>true</verbose>
<fork>false</fork>
<forkCount>0</forkCount>
<argLine>-Xmx1024m</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<cglib.version>3.2.4</cglib.version>
<nosqlunit.version>0.10.0</nosqlunit.version>
<embedded-redis.version>0.6</embedded-redis.version>
</properties>
</project>
@@ -0,0 +1,13 @@
package com.baeldung.spring.data.reactive.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringRedisReactiveApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRedisReactiveApplication.class, args);
}
}
@@ -0,0 +1,51 @@
package com.baeldung.spring.data.reactive.redis.config;
import com.baeldung.spring.data.reactive.redis.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveKeyCommands;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.connection.ReactiveStringCommands;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.PreDestroy;
@Configuration
public class RedisConfig {
@Autowired
RedisConnectionFactory factory;
@Bean
public ReactiveRedisTemplate<String, Employee> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
Jackson2JsonRedisSerializer<Employee> serializer = new Jackson2JsonRedisSerializer<>(Employee.class);
RedisSerializationContext.RedisSerializationContextBuilder<String, Employee> builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer());
RedisSerializationContext<String, Employee> context = builder.value(serializer)
.build();
return new ReactiveRedisTemplate<>(factory, context);
}
@Bean
public ReactiveKeyCommands keyCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) {
return reactiveRedisConnectionFactory.getReactiveConnection()
.keyCommands();
}
@Bean
public ReactiveStringCommands stringCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) {
return reactiveRedisConnectionFactory.getReactiveConnection()
.stringCommands();
}
@PreDestroy
public void cleanRedis() {
factory.getConnection()
.flushDb();
}
}
@@ -0,0 +1,21 @@
package com.baeldung.spring.data.reactive.redis.model;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Employee implements Serializable {
private static final long serialVersionUID = 1603714798906422731L;
private String id;
private String name;
private String department;
}
@@ -0,0 +1,13 @@
package com.baeldung.spring.data.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringRedisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRedisApplication.class, args);
}
}
@@ -0,0 +1,60 @@
package com.baeldung.spring.data.redis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import com.baeldung.spring.data.redis.queue.MessagePublisher;
import com.baeldung.spring.data.redis.queue.RedisMessagePublisher;
import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber;
@Configuration
@ComponentScan("com.baeldung.spring.data.redis")
@EnableRedisRepositories(basePackages = "com.baeldung.spring.data.redis.repo")
@PropertySource("classpath:application.properties")
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(jedisConnectionFactory());
template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
return template;
}
@Bean
MessageListenerAdapter messageListener() {
return new MessageListenerAdapter(new RedisMessageSubscriber());
}
@Bean
RedisMessageListenerContainer redisContainer() {
final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(jedisConnectionFactory());
container.addMessageListener(messageListener(), topic());
return container;
}
@Bean
MessagePublisher redisPublisher() {
return new RedisMessagePublisher(redisTemplate(), topic());
}
@Bean
ChannelTopic topic() {
return new ChannelTopic("pubsub:queue");
}
}
@@ -0,0 +1,62 @@
package com.baeldung.spring.data.redis.model;
import java.io.Serializable;
import org.springframework.data.redis.core.RedisHash;
@RedisHash("Student")
public class Student implements Serializable {
public enum Gender {
MALE, FEMALE
}
private String id;
private String name;
private Gender gender;
private int grade;
public Student(String id, String name, Gender gender, int grade) {
this.id = id;
this.name = name;
this.gender = gender;
this.grade = grade;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", gender=" + gender + ", grade=" + grade + '}';
}
}
@@ -0,0 +1,6 @@
package com.baeldung.spring.data.redis.queue;
public interface MessagePublisher {
void publish(final String message);
}
@@ -0,0 +1,27 @@
package com.baeldung.spring.data.redis.queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.stereotype.Service;
@Service
public class RedisMessagePublisher implements MessagePublisher {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private ChannelTopic topic;
public RedisMessagePublisher() {
}
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate, final ChannelTopic topic) {
this.redisTemplate = redisTemplate;
this.topic = topic;
}
public void publish(final String message) {
redisTemplate.convertAndSend(topic.getTopic(), message);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.spring.data.redis.queue;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class RedisMessageSubscriber implements MessageListener {
public static List<String> messageList = new ArrayList<String>();
public void onMessage(final Message message, final byte[] pattern) {
messageList.add(message.toString());
System.out.println("Message received: " + new String(message.getBody()));
}
}
@@ -0,0 +1,9 @@
package com.baeldung.spring.data.redis.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.baeldung.spring.data.redis.model.Student;
@Repository
public interface StudentRepository extends CrudRepository<Student, String> {}
@@ -0,0 +1,2 @@
spring.redis.host=localhost
spring.redis.port=6379
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Binary file not shown.

After

Width:  |  Height:  |  Size: 855 B

@@ -0,0 +1,33 @@
package com.baeldung;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import com.baeldung.spring.data.redis.SpringRedisApplication;
import redis.embedded.RedisServerBuilder;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisApplication.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class SpringContextTest {
private static redis.embedded.RedisServer redisServer;
@BeforeClass
public static void startRedisServer() {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() {
redisServer.stop();
}
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,72 @@
package com.baeldung.spring.data.reactive.redis.template;
import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.ReactiveKeyCommands;
import org.springframework.data.redis.connection.ReactiveStringCommands;
import org.springframework.data.redis.connection.ReactiveStringCommands.SetCommand;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import redis.embedded.RedisServerBuilder;
import java.io.IOException;
import java.nio.ByteBuffer;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class RedisKeyCommandsManualTest {
private static redis.embedded.RedisServer redisServer;
@Autowired
private ReactiveKeyCommands keyCommands;
@Autowired
private ReactiveStringCommands stringCommands;
@BeforeClass
public static void startRedisServer() throws IOException {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() throws IOException {
redisServer.stop();
}
@Test
public void givenFluxOfKeys_whenPerformOperations_thenPerformOperations() {
Flux<String> keys = Flux.just("key1", "key2", "key3", "key4");
Flux<SetCommand> generator = keys.map(String::getBytes)
.map(ByteBuffer::wrap)
.map(key -> SetCommand.set(key)
.value(key));
StepVerifier.create(stringCommands.set(generator))
.expectNextCount(4L)
.verifyComplete();
Mono<Long> keyCount = keyCommands.keys(ByteBuffer.wrap("key*".getBytes()))
.flatMapMany(Flux::fromIterable)
.count();
StepVerifier.create(keyCount)
.expectNext(4L)
.verifyComplete();
}
}
@@ -0,0 +1,69 @@
package com.baeldung.spring.data.reactive.redis.template;
import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.ReactiveListOperations;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import redis.embedded.RedisServerBuilder;
import java.io.IOException;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class RedisTemplateListOpsManualTest {
private static final String LIST_NAME = "demo_list";
private static redis.embedded.RedisServer redisServer;
@Autowired
private ReactiveStringRedisTemplate redisTemplate;
private ReactiveListOperations<String, String> reactiveListOps;
@BeforeClass
public static void startRedisServer() throws IOException {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 128M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() throws IOException {
redisServer.stop();
}
@Before
public void setup() {
reactiveListOps = redisTemplate.opsForList();
}
@Test
public void givenListAndValues_whenLeftPushAndLeftPop_thenLeftPushAndLeftPop() {
Mono<Long> lPush = reactiveListOps.leftPushAll(LIST_NAME, "first", "second")
.log("Pushed");
StepVerifier.create(lPush)
.expectNext(2L)
.verifyComplete();
Mono<String> lPop = reactiveListOps.leftPop(LIST_NAME)
.log("Popped");
StepVerifier.create(lPop)
.expectNext("second")
.verifyComplete();
}
}
@@ -0,0 +1,93 @@
package com.baeldung.spring.data.reactive.redis.template;
import java.io.IOException;
import java.time.Duration;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.ReactiveValueOperations;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication;
import com.baeldung.spring.data.reactive.redis.model.Employee;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import redis.embedded.RedisServerBuilder;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class RedisTemplateValueOpsManualTest {
private static redis.embedded.RedisServer redisServer;
@Autowired
private ReactiveRedisTemplate<String, Employee> redisTemplate;
private ReactiveValueOperations<String, Employee> reactiveValueOps;
@BeforeClass
public static void startRedisServer() throws IOException {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() throws IOException {
redisServer.stop();
}
@Before
public void setup() {
reactiveValueOps = redisTemplate.opsForValue();
}
@Test
public void givenEmployee_whenSet_thenSet() {
Mono<Boolean> result = reactiveValueOps.set("123", new Employee("123", "Bill", "Accounts"));
StepVerifier.create(result)
.expectNext(true)
.verifyComplete();
}
@Test
public void givenEmployeeId_whenGet_thenReturnsEmployee() {
Mono<Employee> fetchedEmployee = reactiveValueOps.get("123");
StepVerifier.create(fetchedEmployee)
.expectNext(new Employee("123", "Bill", "Accounts"))
.verifyComplete();
}
@Test
public void givenEmployee_whenSetWithExpiry_thenSetsWithExpiryTime() throws InterruptedException {
Mono<Boolean> result = reactiveValueOps.set("129", new Employee("129", "John", "Programming"), Duration.ofSeconds(1));
Mono<Employee> fetchedEmployee = reactiveValueOps.get("129");
StepVerifier.create(result)
.expectNext(true)
.verifyComplete();
Thread.sleep(2000L);
StepVerifier.create(fetchedEmployee)
.expectNextCount(0L)
.verifyComplete();
}
}
@@ -0,0 +1,48 @@
package com.baeldung.spring.data.redis;
import com.baeldung.spring.data.redis.queue.RedisMessagePublisher;
import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringRunner;
import redis.embedded.RedisServerBuilder;
import java.util.UUID;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisApplication.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class RedisMessageListenerManualTest {
private static redis.embedded.RedisServer redisServer;
@Autowired
private RedisMessagePublisher redisMessagePublisher;
@BeforeClass
public static void startRedisServer() {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() {
redisServer.stop();
}
@Test
public void testOnMessage() throws Exception {
String message = "Message " + UUID.randomUUID();
redisMessagePublisher.publish(message);
Thread.sleep(1000);
assertTrue(RedisMessageSubscriber.messageList.get(0).contains(message));
}
}
@@ -0,0 +1,83 @@
package com.baeldung.spring.data.redis.repo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.redis.config.RedisConfig;
import com.baeldung.spring.data.redis.model.Student;
import redis.embedded.RedisServerBuilder;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RedisConfig.class)
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
public class StudentRepositoryManualTest {
@Autowired
private StudentRepository studentRepository;
private static redis.embedded.RedisServer redisServer;
@BeforeClass
public static void startRedisServer() throws IOException {
redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 128M").build();
redisServer.start();
}
@AfterClass
public static void stopRedisServer() throws IOException {
redisServer.stop();
}
@Test
public void whenSavingStudent_thenAvailableOnRetrieval() throws Exception {
final Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.save(student);
final Student retrievedStudent = studentRepository.findById(student.getId()).get();
assertEquals(student.getId(), retrievedStudent.getId());
}
@Test
public void whenUpdatingStudent_thenAvailableOnRetrieval() throws Exception {
final Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.save(student);
student.setName("Richard Watson");
studentRepository.save(student);
final Student retrievedStudent = studentRepository.findById(student.getId()).get();
assertEquals(student.getName(), retrievedStudent.getName());
}
@Test
public void whenSavingStudents_thenAllShouldAvailableOnRetrieval() throws Exception {
final Student engStudent = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
final Student medStudent = new Student("Med2015001", "Gareth Houston", Student.Gender.MALE, 2);
studentRepository.save(engStudent);
studentRepository.save(medStudent);
List<Student> students = new ArrayList<>();
studentRepository.findAll().forEach(students::add);
assertEquals(students.size(), 2);
}
@Test
public void whenDeletingStudent_thenNotAvailableOnRetrieval() throws Exception {
final Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.save(student);
studentRepository.deleteById(student.getId());
final Student retrievedStudent = studentRepository.findById(student.getId()).orElse(null);
assertNull(retrievedStudent);
}
}

Some files were not shown because too many files have changed in this diff Show More