diff --git a/.gitattributes b/.gitattributes index 280866bcb..2e1afeb8d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ *.xml text eol=lf +*.yaml text eol=lf \ No newline at end of file diff --git a/.github/labeler.yml b/.github/labeler.yml index 7606e1a7d..5c5d96a00 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -74,6 +74,10 @@ - changed-files: - any-glob-to-any-file: - jpa/boot-hibernate2ndlevelcache-sample/**/* +"component: jpa-jooq": + - changed-files: + - any-glob-to-any-file: + - jpa/boot-jpa-jooq-sample/**/* "component: jpa-lock": - changed-files: - any-glob-to-any-file: @@ -145,6 +149,7 @@ - jpa/boot-data-envers/pom.xml - jpa/boot-data-multipledatasources/pom.xml - jpa/boot-hibernate2ndlevelcache-sample/pom.xml + - jpa/boot-jpa-jooq-sample/pom.xml - jpa/boot-data-jpa-locks/pom.xml - jpa/boot-read-replica-postgresql/pom.xml - jpa/keyset-pagination/blaze-persistence/pom.xml diff --git a/.github/workflows/boot-jpa-jooq-sample.yml b/.github/workflows/boot-jpa-jooq-sample.yml new file mode 100644 index 000000000..2b5751b29 --- /dev/null +++ b/.github/workflows/boot-jpa-jooq-sample.yml @@ -0,0 +1,39 @@ +name: boot-jpa-jooq-sample + +on: + push: + paths: + - "jpa/boot-jpa-jooq-sample/**" + branches: [main] + pull_request: + paths: + - "jpa/boot-jpa-jooq-sample/**" + types: + - opened + - synchronize + - reopened + +jobs: + build: + name: Run Unit & Integration Tests + runs-on: ubuntu-latest + defaults: + run: + working-directory: "jpa/boot-jpa-jooq-sample" + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + + - name: Set up JDK 21 + uses: actions/setup-java@v4.6.0 + with: + java-version: 21 + distribution: "temurin" + cache: "maven" + + - name: Grant execute permission for mvnw + run: chmod +x mvnw + + - name: Build and analyze + run: ./mvnw clean verify diff --git a/SUMMARY.md b/SUMMARY.md index f3dd2675d..f1a378c2f 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -29,6 +29,7 @@ * [multiple datasources using Spring Boot](jpa/boot-data-multipledatasources/README.md), * [spring-boot-hibernate2ndlevelcache-sample](jpa/boot-hibernate2ndlevelcache-sample/README.md) * [JNDI in embedded Tomcat](jpa/boot-jndi-sample/README.md) + * [JPA Jooq Marriage](jpa/boot-jpa-jooq-sample/README.md) * [JPA locks implementation](jpa/boot-jpa-locks/README.md) * [read-replica-with-spring-boot](jpa/boot-read-replica-postgresql/README.md) * [KeySet Pagination Using Blaze](jpa/keyset-pagination/blaze-persistence/README.md) diff --git a/jpa/boot-jpa-jooq-sample/.mvn/wrapper/maven-wrapper.properties b/jpa/boot-jpa-jooq-sample/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..d58dfb70b --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/jpa/boot-jpa-jooq-sample/Dockerfile b/jpa/boot-jpa-jooq-sample/Dockerfile new file mode 100644 index 000000000..51282e934 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/Dockerfile @@ -0,0 +1,23 @@ +FROM eclipse-temurin:21.0.5_11-jre-alpine as builder +WORKDIR /app +ARG JAR_FILE=target/boot-jpa-jooq-0.0.1-SNAPSHOT.jar +COPY ${JAR_FILE} application.jar +RUN java -Djarmode=layertools -jar application.jar extract + +# the second stage of our build will copy the extracted layers +FROM eclipse-temurin:21.0.5_11-jre-alpine +LABEL maintainer="rajadilipkolli" \ + description="Spring Boot application with JPA and jOOQ integration" \ + version="0.0.1-SNAPSHOT" +WORKDIR /app +COPY --from=builder application/dependencies/ ./ +COPY --from=builder application/spring-boot-loader/ ./ +COPY --from=builder application/snapshot-dependencies/ ./ +COPY --from=builder application/application/ ./ +ARG MAX_RAM_PERCENTAGE=75.0 +ARG INITIAL_RAM_PERCENTAGE=50.0 +ENV JAVA_OPTS="-XX:MaxRAMPercentage=${MAX_RAM_PERCENTAGE} -XX:InitialRAMPercentage=${INITIAL_RAM_PERCENTAGE}" +ENTRYPOINT ["sh", "-c", "java ${JAVA_OPTS} org.springframework.boot.loader.launch.JarLauncher"] + +HEALTHCHECK --interval=30s --timeout=3s \ + CMD wget --quiet --tries=1 --spider http://localhost:8080/actuator/health || exit 1 diff --git a/jpa/boot-jpa-jooq-sample/README.md b/jpa/boot-jpa-jooq-sample/README.md new file mode 100644 index 000000000..a3af2285c --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/README.md @@ -0,0 +1,52 @@ +# boot-jpa-jooq-sample + +This project demonstrates the integration of JPA and jOOQ within a Spring Boot application. + +### Format code + +This project uses Spotless to maintain consistent code formatting. Run the following command to format all files: + +```shell +./mvnw spotless:apply +``` + +### Run tests + +```shell +./mvnw clean verify +``` + +### Run locally + +Ensure you have Docker and Maven installed. Then: + +1. Start the required PostgreSQL database: + +```shell +docker-compose -f docker/docker-compose.yml up -d +``` + +2. Run the application with the local profile (uses local database): + +```shell +./mvnw spring-boot:run -Dspring-boot.run.profiles=local +``` + +### Using Testcontainers at Development Time + +Testcontainers provides isolated, throwaway instances of the PostgreSQL database for testing. +This allows you to run the application without setting up a local database. + +There are two ways to run the application with Testcontainers: + +You can run `TestJpaJooqApplication.java` from your IDE directly. +Alternatively, use Maven: + +```shell +./mvnw spring-boot:test-run +``` + + +### Useful Links +* [Swagger UI](http://localhost:8080/swagger-ui.html) - API documentation and testing interface +* [Actuator Endpoints](http://localhost:8080/actuator) - Application monitoring and management diff --git a/jpa/boot-jpa-jooq-sample/docker/.env b/jpa/boot-jpa-jooq-sample/docker/.env new file mode 100644 index 000000000..0c1dfdc38 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/docker/.env @@ -0,0 +1,3 @@ +POSTGRES_DB=appdb +POSTGRES_USER=appuser +POSTGRES_PASSWORD=secret diff --git a/jpa/boot-jpa-jooq-sample/docker/docker-compose-app.yml b/jpa/boot-jpa-jooq-sample/docker/docker-compose-app.yml new file mode 100644 index 000000000..7e47d8a34 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/docker/docker-compose-app.yml @@ -0,0 +1,17 @@ +version: '3.8' +services: + + boot-jpa-jooq-sample: + build: .. + ports: + - "18080:8080" + - "18787:8787" + restart: always + depends_on: + - postgresqldb + environment: + - SPRING_PROFILES_ACTIVE=docker + - SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.postgresql.Driver + - SPRING_DATASOURCE_URL=jdbc:postgresql://postgresqldb:5432/${POSTGRES_DB} + - SPRING_DATASOURCE_USERNAME=${POSTGRES_USER} + - SPRING_DATASOURCE_PASSWORD=${POSTGRES_PASSWORD} diff --git a/jpa/boot-jpa-jooq-sample/docker/docker-compose.yml b/jpa/boot-jpa-jooq-sample/docker/docker-compose.yml new file mode 100644 index 000000000..807d34441 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/docker/docker-compose.yml @@ -0,0 +1,48 @@ +version: '3.8' +services: + + postgresqldb: + image: postgres:17.2-alpine + hostname: postgresqldb + extra_hosts: [ 'host.docker.internal:host-gateway' ] + environment: + - POSTGRES_USER=appuser + - POSTGRES_PASSWORD=secret + - POSTGRES_DB=appdb + healthcheck: + test: ["CMD-SHELL", "pg_isready -U appuser -d appdb"] + interval: 10s + timeout: 5s + retries: 5 + ports: + - "5432:5432" + networks: + - demo-network + + pgadmin: + image: dpage/pgadmin4 + extra_hosts: [ 'host.docker.internal:host-gateway' ] + environment: + - PGADMIN_DEFAULT_EMAIL=pgadmin4@pgadmin.org + - PGADMIN_DEFAULT_PASSWORD=admin + - PGADMIN_CONFIG_SERVER_MODE=False + - PGADMIN_CONFIG_MASTER_PASSWORD_REQUIRED=False + ports: + - "5050:80" + depends_on: + postgresqldb: + condition: service_started + volumes: + - ./docker_pgadmin_servers.json:/pgadmin4/servers.json + entrypoint: + - "/bin/sh" + - "-c" + - "/bin/echo 'postgresqldb:5432:*:appuser:secret' > /tmp/pgpassfile && chmod 600 /tmp/pgpassfile && /entrypoint.sh" + restart: unless-stopped + networks: + - demo-network + + +networks: + demo-network: + driver: bridge \ No newline at end of file diff --git a/jpa/boot-jpa-jooq-sample/docker/docker_pgadmin_servers.json b/jpa/boot-jpa-jooq-sample/docker/docker_pgadmin_servers.json new file mode 100644 index 000000000..7e977699f --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/docker/docker_pgadmin_servers.json @@ -0,0 +1,14 @@ +{ + "Servers": { + "1": { + "Name": "Docker Compose DB", + "Group": "Servers", + "Port": 5432, + "Username": "appuser", + "Host": "postgresqldb", + "SSLMode": "prefer", + "MaintenanceDB": "appdb", + "PassFile": "/tmp/pgpassfile" + } + } +} \ No newline at end of file diff --git a/jpa/boot-jpa-jooq-sample/mvnw b/jpa/boot-jpa-jooq-sample/mvnw new file mode 100755 index 000000000..19529ddf8 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/jpa/boot-jpa-jooq-sample/mvnw.cmd b/jpa/boot-jpa-jooq-sample/mvnw.cmd new file mode 100644 index 000000000..b150b91ed --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/jpa/boot-jpa-jooq-sample/pom.xml b/jpa/boot-jpa-jooq-sample/pom.xml new file mode 100644 index 000000000..f40e9a8e4 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/pom.xml @@ -0,0 +1,269 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.1 + + + com.example.learning + boot-jpa-jooq-sample + 0.0.1-SNAPSHOT + boot-jpa-jooq-sample + Marriage of Jooq and JPA + + + 21 + 2.8.0 + 0.0.4 + 2.43.0 + + ${project.build.directory}/test-results + ${project.testresult.directory}/test + ${project.testresult.directory}/integrationTest + + + + + + org.springframework.boot + spring-boot-actuator + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-jooq + + + org.springframework.boot + spring-boot-starter-web + + + + org.liquibase + liquibase-core + + + org.postgresql + postgresql + runtime + + + net.ttddyy.observation + datasource-micrometer-spring-boot + 1.0.6 + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + ${springdoc-openapi.version} + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-testcontainers + test + + + org.testcontainers + junit-jupiter + test + + + org.testcontainers + postgresql + test + + + + + + + org.hibernate.orm.tooling + hibernate-enhance-maven-plugin + ${hibernate.version} + + + enhance + + enhance + + + true + true + true + + + + + + org.graalvm.buildtools + native-maven-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + org.testcontainers + testcontainers-jooq-codegen-maven-plugin + ${testcontainers-jooq-codegen-maven-plugin.version} + + + org.testcontainers + postgresql + ${testcontainers.version} + + + org.postgresql + postgresql + ${postgresql.version} + + + + + generate-jooq-sources + + generate + + generate-sources + + + + POSTGRES + + postgres:17.2-alpine + + + db.changelog-master.yaml + src/main/resources/db/changelog + public + + + + + + .* + DATABASECHANGELOG.* + public + + + com.example.learning.db + target/generated-sources/jooq + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + generate-sources + + add-source + + + + ${project.basedir}/target/generated-sources/jooq + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + alphabetical + ${junit.utReportFolder} + + **/*IT* + **/*IntTest* + **/*IntegrationTest* + + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + ${project.build.outputDirectory} + alphabetical + ${junit.itReportFolder} + + **/*IT* + **/*IntTest* + **/*IntegrationTest* + + + + + integration-test + + integration-test + + + + verify + + verify + + + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + + + 2.50.0 + + + + + + + + + compile + + check + + + + + + + + \ No newline at end of file diff --git a/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/JpaJooqApplication.java b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/JpaJooqApplication.java new file mode 100644 index 000000000..a0a745d77 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/JpaJooqApplication.java @@ -0,0 +1,12 @@ +package com.example.learning; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class JpaJooqApplication { + + public static void main(String[] args) { + SpringApplication.run(JpaJooqApplication.class, args); + } +} diff --git a/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/config/JpaConfig.java b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/config/JpaConfig.java new file mode 100644 index 000000000..cdbe0fd9b --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/config/JpaConfig.java @@ -0,0 +1,8 @@ +package com.example.learning.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@EnableJpaAuditing(modifyOnCreate = false) +@Configuration(proxyBeanMethods = false) +public class JpaConfig {} diff --git a/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/Auditable.java b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/Auditable.java new file mode 100644 index 000000000..aa6cf46e1 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/Auditable.java @@ -0,0 +1,39 @@ +package com.example.learning.entities; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import java.time.LocalDateTime; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +@EntityListeners(AuditingEntityListener.class) +@MappedSuperclass +public abstract class Auditable { + + @CreatedDate + @Column(nullable = false, updatable = false) + protected LocalDateTime createdAt; + + @LastModifiedDate + protected LocalDateTime modifiedAt; + + public LocalDateTime getCreatedAt() { + return createdAt; + } + + public Auditable setCreatedAt(LocalDateTime createdAt) { + this.createdAt = createdAt; + return this; + } + + public LocalDateTime getModifiedAt() { + return modifiedAt; + } + + public Auditable setModifiedAt(LocalDateTime modifiedAt) { + this.modifiedAt = modifiedAt; + return this; + } +} diff --git a/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/Post.java b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/Post.java new file mode 100644 index 000000000..03a38a86c --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/Post.java @@ -0,0 +1,202 @@ +package com.example.learning.entities; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; +import java.io.Serial; +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import org.hibernate.Hibernate; +import org.hibernate.annotations.BatchSize; + +/** + * Represents a blog post entity with associated comments, tags, and details. + * This entity uses bidirectional relationships and implements proper relationship management. + */ +@Entity +@Table(name = "posts") +public class Post extends Auditable implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + private String title; + + private String content; + + private boolean published; + + private LocalDateTime publishedAt; + + @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true) + @BatchSize(size = 20) + private List comments = new ArrayList<>(); + + @OneToOne(mappedBy = "post", cascade = CascadeType.ALL, optional = false) + private PostDetails details; + + @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true) + @BatchSize(size = 20) + private List tags = new ArrayList<>(); + + public Post() {} + + public Long getId() { + return id; + } + + public Post setId(Long id) { + this.id = id; + return this; + } + + public String getTitle() { + return title; + } + + public Post setTitle(String title) { + this.title = title; + return this; + } + + public String getContent() { + return content; + } + + public Post setContent(String content) { + this.content = content; + return this; + } + + public boolean isPublished() { + return published; + } + + public Post setPublished(boolean published) { + this.published = published; + return this; + } + + public LocalDateTime getPublishedAt() { + return publishedAt; + } + + public Post setPublishedAt(LocalDateTime publishedAt) { + this.publishedAt = publishedAt; + return this; + } + + public List getComments() { + return comments; + } + + public Post setComments(List comments) { + if (comments == null) { + comments = new ArrayList<>(); + } + this.comments = comments; + return this; + } + + public PostDetails getDetails() { + return details; + } + + public List getTags() { + return tags; + } + + public Post setTags(List tags) { + if (tags == null) { + tags = new ArrayList<>(); + } + this.tags = tags; + return this; + } + + public Post publish() { + this.published = true; + this.publishedAt = LocalDateTime.now(); + return this; + } + + public Post unpublish() { + this.published = false; + this.publishedAt = null; + return this; + } + + public void addComment(PostComment comment) { + this.comments.add(comment); + comment.setPost(this); + } + + public void removeComment(PostComment comment) { + this.comments.remove(comment); + comment.setPost(null); + } + + public void setDetails(PostDetails details) { + if (details == null) { + if (this.details != null) { + this.details.setPost(null); + } + } else { + details.setPost(this); + } + this.details = details; + } + + public void addTag(Tag tag) { + PostTag postTag = new PostTag(this, tag); + this.tags.add(postTag); + } + + public void removeTag(Tag tag) { + if (tag == null) { + return; + } + this.tags.removeIf(postTag -> { + if (postTag.getPost().equals(this) && postTag.getTag().equals(tag)) { + postTag.setPost(null); + postTag.setTag(null); + return true; + } + return false; + }); + } + + @Override + public String toString() { + return "Post{" + "id=" + + id + ", title='" + + title + '\'' + ", published=" + + published + ", publishedAt=" + + publishedAt + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; + Post post = (Post) o; + return id != null && title != null && Objects.equals(id, post.id) && Objects.equals(this.title, post.title); + } + + @Override + public int hashCode() { + return getClass().hashCode(); + } +} diff --git a/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostComment.java b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostComment.java new file mode 100644 index 000000000..be35a40aa --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostComment.java @@ -0,0 +1,110 @@ +package com.example.learning.entities; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import java.io.Serial; +import java.io.Serializable; +import java.time.OffsetDateTime; +import java.util.Objects; +import org.hibernate.Hibernate; + +@Entity +@Table(name = "post_comments") +public class PostComment extends Auditable implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(nullable = false) + private String title; + + private String content; + + private boolean published; + + private OffsetDateTime publishedAt; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "post_id", nullable = false) + private Post post; + + public PostComment() {} + + public Long getId() { + return id; + } + + public PostComment setId(Long id) { + this.id = id; + return this; + } + + public String getTitle() { + return title; + } + + public PostComment setTitle(String title) { + this.title = title; + return this; + } + + public String getContent() { + return content; + } + + public PostComment setContent(String content) { + this.content = content; + return this; + } + + public boolean isPublished() { + return published; + } + + public PostComment setPublished(boolean published) { + this.published = published; + return this; + } + + public OffsetDateTime getPublishedAt() { + return publishedAt; + } + + public PostComment setPublishedAt(OffsetDateTime publishedAt) { + this.publishedAt = publishedAt; + return this; + } + + public Post getPost() { + return post; + } + + public PostComment setPost(Post post) { + this.post = post; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; + PostComment postComment = (PostComment) o; + return id != null && Objects.equals(id, postComment.id); + } + + @Override + public int hashCode() { + return getClass().hashCode(); + } +} diff --git a/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostDetails.java b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostDetails.java new file mode 100644 index 000000000..52b411a68 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostDetails.java @@ -0,0 +1,92 @@ +package com.example.learning.entities; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.MapsId; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; +import java.io.Serial; +import java.io.Serializable; +import java.util.Objects; + +@Entity +@Table(name = "post_details") +public class PostDetails extends Auditable implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @Id + private Long id; + + private String detailsKey; + + @Column(name = "created_by") + private String createdBy; + + @OneToOne(fetch = FetchType.LAZY) + @MapsId + @JoinColumn(name = "id") + private Post post; + + public PostDetails() {} + + public Long getId() { + return id; + } + + public PostDetails setId(Long id) { + this.id = id; + return this; + } + + public String getDetailsKey() { + return detailsKey; + } + + public PostDetails setDetailsKey(String detailsKey) { + this.detailsKey = detailsKey; + return this; + } + + public String getCreatedBy() { + return createdBy; + } + + public PostDetails setCreatedBy(String createdBy) { + this.createdBy = createdBy; + return this; + } + + public Post getPost() { + return post; + } + + public PostDetails setPost(Post post) { + this.post = post; + return this; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + PostDetails other = (PostDetails) obj; + return Objects.equals(this.createdBy, other.createdBy); + } + + @Override + public int hashCode() { + return Objects.hash(this.createdBy); + } +} diff --git a/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostTag.java b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostTag.java new file mode 100644 index 000000000..afbd4a38e --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostTag.java @@ -0,0 +1,102 @@ +package com.example.learning.entities; + +import jakarta.persistence.Column; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.MapsId; +import jakarta.persistence.Table; +import java.io.Serial; +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.Objects; + +@Entity(name = "PostTag") +@Table(name = "post_tag") +public class PostTag implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @EmbeddedId + private PostTagId id; + + @ManyToOne(fetch = FetchType.LAZY) + @MapsId("postId") + @JoinColumn(name = "post_id") + private Post post; + + @ManyToOne(fetch = FetchType.LAZY) + @MapsId("tagId") + @JoinColumn(name = "tag_id") + private Tag tag; + + @Column(name = "created_on") + private LocalDateTime createdOn = LocalDateTime.now(); + + public PostTag() { + this.createdOn = LocalDateTime.now(); + } + + public PostTag(Post post, Tag tag) { + this.post = post; + this.tag = tag; + this.id = new PostTagId(post.getId(), tag.getId()); + } + + public PostTagId getId() { + return id; + } + + public PostTag setId(PostTagId id) { + this.id = id; + return this; + } + + public Post getPost() { + return post; + } + + public PostTag setPost(Post post) { + this.post = post; + return this; + } + + public Tag getTag() { + return tag; + } + + public PostTag setTag(Tag tag) { + this.tag = tag; + return this; + } + + public LocalDateTime getCreatedOn() { + return createdOn; + } + + public PostTag setCreatedOn(LocalDateTime createdOn) { + this.createdOn = createdOn; + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + PostTag that = (PostTag) o; + return Objects.equals(this.post, that.post) && Objects.equals(this.tag, that.tag); + } + + @Override + public int hashCode() { + return Objects.hash(this.post, this.tag); + } +} diff --git a/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostTagId.java b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostTagId.java new file mode 100644 index 000000000..c906ab9eb --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/PostTagId.java @@ -0,0 +1,7 @@ +package com.example.learning.entities; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; + +@Embeddable +public record PostTagId(@Column(name = "post_id") Long postId, @Column(name = "tag_id") Long tagId) {} diff --git a/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/Tag.java b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/Tag.java new file mode 100644 index 000000000..c73ab0d22 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/java/com/example/learning/entities/Tag.java @@ -0,0 +1,77 @@ +package com.example.learning.entities; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; +import java.io.Serial; +import java.io.Serializable; +import java.util.Objects; + +@Entity +@Table( + name = "tags", + uniqueConstraints = {@UniqueConstraint(columnNames = "tag_name", name = "uc_tag_name")}) +public class Tag implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(nullable = false, unique = true, name = "tag_name") + private String tagName; + + private String tagDescription; + + public Tag() {} + + public Long getId() { + return id; + } + + public Tag setId(Long id) { + this.id = id; + return this; + } + + public String getTagName() { + return tagName; + } + + public Tag setTagName(String tagName) { + this.tagName = tagName; + return this; + } + + public String getTagDescription() { + return tagDescription; + } + + public Tag setTagDescription(String tagDescription) { + this.tagDescription = tagDescription; + return this; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + Tag other = (Tag) obj; + return Objects.equals(this.tagName, other.tagName); + } + + @Override + public int hashCode() { + return Objects.hash(this.tagName); + } +} diff --git a/jpa/boot-jpa-jooq-sample/src/main/resources/application.properties b/jpa/boot-jpa-jooq-sample/src/main/resources/application.properties new file mode 100644 index 000000000..4fc10e89a --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/resources/application.properties @@ -0,0 +1,30 @@ +spring.application.name=boot-jpa-jooq-sample +server.port=8080 +server.shutdown=graceful +spring.jmx.enabled=false +spring.mvc.problemdetails.enabled=true + +################ Actuator ##################### +management.endpoints.web.exposure.include=configprops,env,health,info,logfile,loggers,metrics,prometheus +management.endpoint.health.access=read_only + +################ Database ##################### +spring.jpa.show-sql=false +spring.jpa.open-in-view=false +spring.data.jpa.repositories.bootstrap-mode=deferred +spring.datasource.hikari.auto-commit=false +spring.datasource.hikari.pool-name=HikariPool-${spring.application.name} +spring.datasource.hikari.data-source-properties.ApplicationName=${spring.application.name} +spring.jpa.hibernate.ddl-auto=none +#spring.jpa.properties.hibernate.format_sql=true +spring.jpa.properties.hibernate.jdbc.time_zone=UTC +spring.jpa.properties.hibernate.generate_statistics=false +spring.jpa.properties.hibernate.jdbc.batch_size=25 +spring.jpa.properties.hibernate.order_inserts=true +spring.jpa.properties.hibernate.order_updates=true +spring.jpa.properties.hibernate.query.fail_on_pagination_over_collection_fetch=true +spring.jpa.properties.hibernate.query.in_clause_parameter_padding=true +spring.jpa.properties.hibernate.query.plan_cache_max_size=4096 +spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true +spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true +spring.threads.virtual.enabled=true diff --git a/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/db.changelog-master.yaml b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/db.changelog-master.yaml new file mode 100644 index 000000000..60e0fdb88 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/db.changelog-master.yaml @@ -0,0 +1,5 @@ +databaseChangeLog: + - includeAll: + path: migration/ + errorIfMissingOrEmpty: true + relativeToChangelogFile: true diff --git a/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/01-create_posts_table.xml b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/01-create_posts_table.xml new file mode 100644 index 000000000..eda99779e --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/01-create_posts_table.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/02-create_post_comments_table.xml b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/02-create_post_comments_table.xml new file mode 100644 index 000000000..33de2fbe9 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/02-create_post_comments_table.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/03-create_post_details_table.xml b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/03-create_post_details_table.xml new file mode 100644 index 000000000..5174079bd --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/03-create_post_details_table.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + One-to-one relationship with posts table, storing additional details for each post + + + + + + + + + + + + + + + + diff --git a/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/04-create_tags_table.xml b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/04-create_tags_table.xml new file mode 100644 index 000000000..d64384c56 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/04-create_tags_table.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/05-create_post_tag_table.xml b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/05-create_post_tag_table.xml new file mode 100644 index 000000000..967064de9 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/main/resources/db/changelog/migration/05-create_post_tag_table.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + diff --git a/jpa/boot-jpa-jooq-sample/src/test/java/com/example/learning/SchemaValidationTest.java b/jpa/boot-jpa-jooq-sample/src/test/java/com/example/learning/SchemaValidationTest.java new file mode 100644 index 000000000..b91fe99f5 --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/test/java/com/example/learning/SchemaValidationTest.java @@ -0,0 +1,24 @@ +package com.example.learning; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.example.learning.common.SQLContainerConfig; +import com.zaxxer.hikari.HikariDataSource; +import javax.sql.DataSource; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.context.annotation.Import; + +@DataJpaTest(properties = {"spring.jpa.hibernate.ddl-auto=validate"}) +@Import(SQLContainerConfig.class) +class SchemaValidationTest { + + @Autowired + private DataSource dataSource; + + @Test + void validateJpaMappingsWithDbSchema() { + assertThat(dataSource).isInstanceOf(HikariDataSource.class); + } +} diff --git a/jpa/boot-jpa-jooq-sample/src/test/java/com/example/learning/TestJpaJooqApplication.java b/jpa/boot-jpa-jooq-sample/src/test/java/com/example/learning/TestJpaJooqApplication.java new file mode 100644 index 000000000..0c31cab5a --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/test/java/com/example/learning/TestJpaJooqApplication.java @@ -0,0 +1,13 @@ +package com.example.learning; + +import com.example.learning.common.SQLContainerConfig; +import org.springframework.boot.SpringApplication; + +class TestJpaJooqApplication { + + public static void main(String[] args) { + SpringApplication.from(JpaJooqApplication::main) + .with(SQLContainerConfig.class) + .run(args); + } +} diff --git a/jpa/boot-jpa-jooq-sample/src/test/java/com/example/learning/common/SQLContainerConfig.java b/jpa/boot-jpa-jooq-sample/src/test/java/com/example/learning/common/SQLContainerConfig.java new file mode 100644 index 000000000..b5252122f --- /dev/null +++ b/jpa/boot-jpa-jooq-sample/src/test/java/com/example/learning/common/SQLContainerConfig.java @@ -0,0 +1,17 @@ +package com.example.learning.common; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.annotation.Bean; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.utility.DockerImageName; + +@TestConfiguration(proxyBeanMethods = false) +public class SQLContainerConfig { + + @Bean + @ServiceConnection + PostgreSQLContainer postgreSQLContainer() { + return new PostgreSQLContainer<>(DockerImageName.parse("postgres").withTag("17.2-alpine")); + } +} diff --git a/pom.xml b/pom.xml index 83e24b969..534253b0a 100644 --- a/pom.xml +++ b/pom.xml @@ -39,6 +39,7 @@ jpa/boot-data-multipledatasources jpa/boot-hibernate2ndlevelcache-sample jpa/boot-jndi-sample + jpa/boot-jpa-jooq-sample jpa/boot-jpa-locks jpa/boot-read-replica-postgresql jpa/keyset-pagination/blaze-persistence