├── .gitignore ├── .travis.yml ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── lib └── .gitkeep ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── example │ │ ├── EclipseLinkJpaConfiguration.java │ │ ├── ImmutableEntity.java │ │ ├── LatestMouse.java │ │ ├── LatestMouseRepository.java │ │ ├── Mouse.java │ │ ├── MouseApplication.java │ │ ├── MouseRepository.java │ │ ├── MouseRepositoryEventListener.java │ │ ├── UUIDPersistenceConverter.java │ │ └── UUIDSequence.java └── resources │ ├── application-mysql.yml │ └── application.yml └── test └── java └── com └── example └── MouseApplicationRestTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings/ 4 | bin/ 5 | .gradle/ 6 | build/ 7 | lib/spring-instrument.jar 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | sudo: false 5 | cache: 6 | directories: 7 | - $HOME/.gradle 8 | script: ./gradlew build 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JPA/Eclipselink UUID primary key sample 2 | 3 | Example project for demonstrating an enhanced usage of UUIDs as primary keys in JPA, 4 | using Version 1 (time-based) UUIDs. 5 | 6 | ## Special Features 7 | 8 | The UUID is not, naively serialized as String, but converted into a 16-byte array 9 | for optimized storage. The UUIDs are generated transparently while persisting the 10 | entity. This is achieved by registering a custom UUID sequence generator in EclipseLink. 11 | 12 | The JUG [Java Uuid Generator](https://github.com/cowtowncoder/java-uuid-generator) library 13 | serves as source for generation of (Version-1) UUIDs. 14 | 15 | ## Further references: 16 | 17 | * https://en.wikipedia.org/wiki/Universally_unique_identifier 18 | * https://github.com/cowtowncoder/java-uuid-generator 19 | * http://mysql.rjweb.org/doc.php/uuid 20 | * http://mysqlserverteam.com/storing-uuid-values-in-mysql-tables/ 21 | * https://www.clever-cloud.com/blog/engineering/2015/05/20/why-auto-increment-is-a-terrible-idea/ 22 | * https://wiki.eclipse.org/EclipseLink/Examples/JPA/CustomSequencing 23 | * http://stackoverflow.com/questions/10867405/generating-v5-uuid-what-is-name-and-namespace -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { springBootVersion = '1.4.3.RELEASE' } 3 | repositories { 4 | mavenCentral() 5 | } 6 | dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } 7 | } 8 | 9 | apply plugin: 'java' 10 | apply plugin: 'eclipse' 11 | apply plugin: 'idea' 12 | apply plugin: 'org.springframework.boot' 13 | 14 | jar { 15 | baseName = 'demo' 16 | version = '0.0.1-SNAPSHOT' 17 | } 18 | 19 | sourceCompatibility = 1.8 20 | targetCompatibility = 1.8 21 | 22 | repositories { 23 | mavenCentral() 24 | } 25 | 26 | project.tasks.withType(JavaCompile) { 27 | options.fork = true 28 | options.compilerArgs << '-parameters' 29 | } 30 | 31 | test { 32 | testLogging { 33 | events "passed", "skipped", "failed", "standardOut", "standardError" 34 | } 35 | } 36 | 37 | configurations { 38 | instrument { 39 | description 'classpath for instrument as java agent' 40 | } 41 | } 42 | 43 | dependencies { 44 | // Tooling 45 | compileOnly 'org.projectlombok:lombok:1.16.12' 46 | instrument('org.springframework:spring-instrument') 47 | 48 | // Database 49 | compile("org.springframework.boot:spring-boot-starter-data-jpa") { exclude module: 'hibernate-entitymanager' } 50 | compile 'org.eclipse.persistence:org.eclipse.persistence.jpa:2.6.4' 51 | runtime("com.h2database:h2") 52 | runtime 'mysql:mysql-connector-java' 53 | 54 | // REST 55 | runtime('org.springframework.data:spring-data-rest-hal-browser') 56 | compile("org.springframework.boot:spring-boot-starter-data-rest") 57 | runtime 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' 58 | 59 | // Util 60 | compile 'com.google.guava:guava:20.0' 61 | compile('com.fasterxml.uuid:java-uuid-generator:3.1.3') 62 | 63 | // Testing 64 | testCompile('org.springframework.boot:spring-boot-starter-test') 65 | } 66 | 67 | test { jvmArgs "-javaagent:$project.configurations.instrument.singleFile" } 68 | 69 | bootRun { 70 | jvmArgs "-javaagent:$project.configurations.instrument.singleFile" 71 | systemProperties = System.properties 72 | } 73 | 74 | task copySpringInstrumentJar (type:Copy) { 75 | description = 'Copies the spring-instrument.jar into your lib directory.' 76 | outputs.file project.file('lib/spring-instrument.jar') 77 | from (project.configurations.instrument) 78 | into("lib") 79 | rename { String filename -> filename = 'spring-instrument.jar' } 80 | } 81 | 82 | tasks.idea.dependsOn(project.tasks.copySpringInstrumentJar) 83 | tasks.eclipse.dependsOn(project.tasks.copySpringInstrumentJar) 84 | tasks.processResources.dependsOn(project.tasks.copySpringInstrumentJar) 85 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/otrosien/uuid-jpa-rest-example/0a92868da1942b4385273a60776e51c1fc0a6c67/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Aug 16 14:12:03 CEST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /lib/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/otrosien/uuid-jpa-rest-example/0a92868da1942b4385273a60776e51c1fc0a6c67/lib/.gitkeep -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'uuid-jpa-rest-example' 2 | -------------------------------------------------------------------------------- /src/main/java/com/example/EclipseLinkJpaConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import static com.google.common.collect.Maps.newHashMap; 4 | 5 | import java.util.Map; 6 | 7 | import javax.sql.DataSource; 8 | 9 | import org.eclipse.persistence.config.PersistenceUnitProperties; 10 | import org.springframework.beans.factory.ObjectProvider; 11 | import org.springframework.boot.autoconfigure.domain.EntityScan; 12 | import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration; 13 | import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; 14 | import org.springframework.context.annotation.Configuration; 15 | import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; 16 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 17 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 18 | import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter; 19 | import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter; 20 | import org.springframework.transaction.jta.JtaTransactionManager; 21 | 22 | import com.google.common.collect.ImmutableMap; 23 | 24 | @Configuration 25 | @EnableJpaRepositories 26 | @EnableJpaAuditing 27 | @EntityScan(basePackageClasses = {MouseApplication.class, Jsr310JpaConverters.class}) 28 | public class EclipseLinkJpaConfiguration extends JpaBaseConfiguration { 29 | 30 | protected EclipseLinkJpaConfiguration(DataSource dataSource, JpaProperties properties, 31 | ObjectProvider jtaTransactionManagerProvider) { 32 | super(dataSource, properties, jtaTransactionManagerProvider); 33 | } 34 | 35 | @Override 36 | protected AbstractJpaVendorAdapter createJpaVendorAdapter() { 37 | return new EclipseLinkJpaVendorAdapter(); 38 | } 39 | 40 | @Override 41 | protected Map getVendorProperties() { 42 | final ImmutableMap immutableMap = ImmutableMap.builder() // 43 | .put(PersistenceUnitProperties.TABLE_CREATION_SUFFIX, ";") 44 | .put(PersistenceUnitProperties.SESSION_CUSTOMIZER, com.example.UUIDSequence.class.getName()) 45 | .build(); 46 | return newHashMap(immutableMap); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/example/ImmutableEntity.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import static lombok.AccessLevel.PACKAGE; 4 | 5 | import java.time.Instant; 6 | import java.util.UUID; 7 | 8 | import javax.persistence.Basic; 9 | import javax.persistence.Column; 10 | import javax.persistence.EntityListeners; 11 | import javax.persistence.GeneratedValue; 12 | import javax.persistence.Id; 13 | import javax.persistence.MappedSuperclass; 14 | 15 | import org.springframework.data.annotation.CreatedDate; 16 | import org.springframework.data.domain.Persistable; 17 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 18 | 19 | import com.fasterxml.jackson.annotation.JsonIgnore; 20 | import com.fasterxml.jackson.annotation.JsonProperty; 21 | 22 | import lombok.Getter; 23 | import lombok.Setter; 24 | 25 | @SuppressWarnings("serial") 26 | @MappedSuperclass 27 | @EntityListeners({AuditingEntityListener.class}) 28 | public abstract class ImmutableEntity implements Persistable { 29 | 30 | @Id 31 | @Column(columnDefinition="BINARY(16) NOT NULL") 32 | @GeneratedValue(generator="uuid-sequence") 33 | @Getter 34 | @Setter(PACKAGE) 35 | @JsonProperty(value="_id", access=JsonProperty.Access.READ_ONLY) 36 | protected UUID id; 37 | 38 | @Basic 39 | @CreatedDate 40 | @JsonIgnore 41 | @Column(name = "CREATED_AT", nullable = false, insertable = true, updatable = false, columnDefinition = "TIMESTAMP NOT NULL") 42 | private Instant createdAt; 43 | 44 | protected ImmutableEntity() {} 45 | 46 | public ImmutableEntity(UUID id) { 47 | this.id = id; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/example/LatestMouse.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import static javax.persistence.AccessType.FIELD; 4 | 5 | import javax.persistence.Access; 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.Id; 9 | import javax.persistence.Index; 10 | import javax.persistence.OneToOne; 11 | import javax.persistence.Table; 12 | 13 | import lombok.AccessLevel; 14 | import lombok.AllArgsConstructor; 15 | import lombok.Getter; 16 | import lombok.NoArgsConstructor; 17 | 18 | @Entity 19 | @Access(FIELD) 20 | @NoArgsConstructor(access = AccessLevel.PRIVATE) 21 | @AllArgsConstructor 22 | @Table(name = "LATEST_MOUSE", indexes= { 23 | @Index(columnList="ID", unique=true) 24 | }) 25 | public class LatestMouse { 26 | 27 | @Id 28 | @Getter 29 | @Column(name = "NAME", nullable = false, insertable = true, updatable = false) 30 | private String name; 31 | 32 | @OneToOne(optional=false) 33 | @Getter 34 | private Mouse mouse; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/example/LatestMouseRepository.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import java.util.UUID; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Modifying; 7 | import org.springframework.data.rest.core.annotation.RepositoryRestResource; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @RepositoryRestResource(exported=false) 11 | public interface LatestMouseRepository extends JpaRepository { 12 | 13 | @Modifying 14 | @Transactional 15 | void deleteByMouse(Mouse mouse); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/example/Mouse.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import static lombok.AccessLevel.PRIVATE; 4 | 5 | import javax.persistence.Access; 6 | import javax.persistence.AccessType; 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.Index; 10 | import javax.persistence.Table; 11 | 12 | import lombok.EqualsAndHashCode; 13 | import lombok.Getter; 14 | import lombok.NoArgsConstructor; 15 | import lombok.Setter; 16 | 17 | @Entity 18 | @Access(AccessType.FIELD) 19 | @Table(name="MOUSE", indexes= { 20 | @Index(columnList="NAME", unique=false) 21 | }) 22 | @NoArgsConstructor(access=PRIVATE) 23 | @EqualsAndHashCode(of="name", callSuper=false) 24 | public class Mouse extends ImmutableEntity { 25 | 26 | private static final long serialVersionUID = 9132197821372047114L; 27 | 28 | // stable identifier. 29 | @Getter 30 | @Column(name = "NAME", nullable = false, insertable = true, updatable = false) 31 | private String name; 32 | 33 | @Getter 34 | @Setter 35 | @Column(name = "AGE", nullable = true, insertable = true, updatable = true) 36 | private Integer age; 37 | 38 | @Override 39 | public String toString() { 40 | return String.format("Mouse [id=%s]", id); 41 | } 42 | 43 | @Override 44 | public boolean isNew() { 45 | return true; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/example/MouseApplication.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.data.rest.core.config.RepositoryRestConfiguration; 7 | import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; 8 | 9 | @SpringBootApplication 10 | public class MouseApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(MouseApplication.class, args); 14 | } 15 | 16 | @Configuration 17 | static class MouseRestConfiguration extends RepositoryRestMvcConfiguration { 18 | 19 | @Override 20 | protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { 21 | config 22 | .setReturnBodyOnCreate(true) 23 | .setReturnBodyOnUpdate(true) 24 | .exposeIdsFor(Mouse.class) 25 | .withEntityLookup() 26 | .forRepository(MouseRepository.class, Mouse::getName, MouseRepository::findLatestMouseByName); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/example/MouseRepository.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import java.util.Optional; 4 | import java.util.UUID; 5 | 6 | import org.springframework.data.domain.Page; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.data.jpa.repository.JpaRepository; 9 | import org.springframework.data.jpa.repository.Query; 10 | 11 | public interface MouseRepository extends JpaRepository { 12 | 13 | @Query("SELECT m FROM Mouse m JOIN LatestMouse lm ON m.id=lm.mouse.id WHERE lm.name=:name") 14 | Optional findLatestMouseByName(String name); 15 | 16 | @Query("SELECT m FROM Mouse m LEFT JOIN LatestMouse lm ON m.id=lm.mouse.id WHERE m.name=:name AND lm.mouse.id IS NULL") 17 | Page findOldMiceByName(String name, Pageable pageable); 18 | 19 | Optional findOneById(UUID id); 20 | 21 | @Override 22 | @Query("SELECT m FROM Mouse m JOIN LatestMouse lm ON lm.mouse.id=m.id") 23 | Page findAll(Pageable pageable); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/example/MouseRepositoryEventListener.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import javax.persistence.EntityManager; 4 | 5 | import org.springframework.data.rest.core.event.AbstractRepositoryEventListener; 6 | import org.springframework.stereotype.Component; 7 | 8 | import lombok.RequiredArgsConstructor; 9 | 10 | @Component 11 | @RequiredArgsConstructor 12 | public class MouseRepositoryEventListener extends AbstractRepositoryEventListener { 13 | 14 | private final EntityManager em; 15 | 16 | private final LatestMouseRepository repo; 17 | 18 | @Override 19 | protected void onAfterCreate(Mouse entity) { 20 | updateLatestMouseTo(entity); 21 | } 22 | 23 | @Override 24 | protected void onBeforeSave(Mouse entity) { 25 | em.detach(entity); 26 | generateNewId(entity); 27 | updateLatestMouseTo(entity); 28 | } 29 | 30 | @Override 31 | protected void onBeforeDelete(Mouse entity) { 32 | repo.deleteByMouse(entity); 33 | } 34 | 35 | private void updateLatestMouseTo(Mouse entity) { 36 | repo.save(new LatestMouse(entity.getName(), entity)); 37 | } 38 | 39 | private void generateNewId(Mouse entity) { 40 | entity.setId(null); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/example/UUIDPersistenceConverter.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import java.util.UUID; 4 | 5 | import javax.persistence.AttributeConverter; 6 | import javax.persistence.Converter; 7 | 8 | @Converter(autoApply=true) 9 | public class UUIDPersistenceConverter implements AttributeConverter { 10 | 11 | @Override 12 | public byte[] convertToDatabaseColumn(UUID uuid) { 13 | if (uuid == null) { 14 | return null; // NOSONAR - be able to persist a null value 15 | } 16 | return ToBytesTransformer.INSTANCE.transform(uuid); 17 | } 18 | 19 | @Override 20 | public UUID convertToEntityAttribute(byte[] binaryData) { 21 | if(binaryData == null) { 22 | return null; 23 | } 24 | if ( binaryData.length != 16 ) { 25 | throw new IllegalArgumentException( "Expecting 16 byte values to construct a UUID" ); 26 | } 27 | return ToBytesTransformer.INSTANCE.parse(binaryData); 28 | } 29 | 30 | static class ToBytesTransformer { 31 | public static final ToBytesTransformer INSTANCE = new ToBytesTransformer(); 32 | 33 | byte[] transform(UUID uuid) { 34 | byte[] bytes = new byte[16]; 35 | System.arraycopy( fromLong( uuid.getMostSignificantBits() ), 0, bytes, 0, 8 ); 36 | System.arraycopy( fromLong( uuid.getLeastSignificantBits() ), 0, bytes, 8, 8 ); 37 | return bytes; 38 | } 39 | 40 | private static byte[] fromLong(long longValue) { 41 | byte[] bytes = new byte[8]; 42 | bytes[0] = (byte) ( longValue >> 56 ); 43 | bytes[1] = (byte) ( ( longValue << 8 ) >> 56 ); 44 | bytes[2] = (byte) ( ( longValue << 16 ) >> 56 ); 45 | bytes[3] = (byte) ( ( longValue << 24 ) >> 56 ); 46 | bytes[4] = (byte) ( ( longValue << 32 ) >> 56 ); 47 | bytes[5] = (byte) ( ( longValue << 40 ) >> 56 ); 48 | bytes[6] = (byte) ( ( longValue << 48 ) >> 56 ); 49 | bytes[7] = (byte) ( ( longValue << 56 ) >> 56 ); 50 | return bytes; 51 | } 52 | 53 | UUID parse(Object value) { 54 | byte[] msb = new byte[8]; 55 | byte[] lsb = new byte[8]; 56 | System.arraycopy( value, 0, msb, 0, 8 ); 57 | System.arraycopy( value, 8, lsb, 0, 8 ); 58 | return new UUID( asLong( msb ), asLong( lsb ) ); 59 | } 60 | 61 | private static long asLong(byte[] bytes) { 62 | long value = 0; 63 | for (int i=0; i<8; i++) { 64 | value = (value << 8) | (bytes[i] & 0xff); 65 | } 66 | return value; 67 | } 68 | 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/example/UUIDSequence.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import java.util.Vector; 4 | 5 | import org.eclipse.persistence.config.SessionCustomizer; 6 | import org.eclipse.persistence.internal.databaseaccess.Accessor; 7 | import org.eclipse.persistence.internal.sessions.AbstractSession; 8 | import org.eclipse.persistence.sequencing.Sequence; 9 | import org.eclipse.persistence.sessions.Session; 10 | 11 | import com.fasterxml.uuid.EthernetAddress; 12 | import com.fasterxml.uuid.Generators; 13 | import com.fasterxml.uuid.impl.TimeBasedGenerator; 14 | 15 | public class UUIDSequence extends Sequence implements SessionCustomizer { 16 | 17 | private static final long serialVersionUID = -8111815193483132234L; 18 | 19 | private static final TimeBasedGenerator UUID_GENERATOR = Generators.timeBasedGenerator(EthernetAddress.fromInterface()); 20 | 21 | private static final UUIDPersistenceConverter CONVERTER = new UUIDPersistenceConverter(); 22 | 23 | public UUIDSequence() { 24 | super(); 25 | } 26 | 27 | public UUIDSequence(String name) { 28 | super(name); 29 | } 30 | 31 | @Override 32 | public Object getGeneratedValue(Accessor accessor, AbstractSession writeSession, String seqName) { 33 | return CONVERTER.convertToDatabaseColumn(UUID_GENERATOR.generate()); 34 | } 35 | 36 | @SuppressWarnings("rawtypes") 37 | @Override 38 | public Vector getGeneratedVector(Accessor accessor, AbstractSession writeSession, String seqName, int size) { 39 | return null; // NOSONAR - this method is unused anyway. 40 | } 41 | 42 | @Override 43 | public void onConnect() { // nothing to do 44 | } 45 | 46 | @Override 47 | public void onDisconnect() { // nothing to do 48 | } 49 | 50 | @Override 51 | public boolean shouldAcquireValueAfterInsert() { 52 | return false; 53 | } 54 | 55 | @Override 56 | public boolean shouldUseTransaction() { 57 | return false; 58 | } 59 | 60 | @Override 61 | public boolean shouldUsePreallocation() { 62 | return false; 63 | } 64 | 65 | @Override 66 | public void customize(Session session) throws Exception { 67 | UUIDSequence sequence = new UUIDSequence("uuid-sequence"); 68 | session.getLogin().addSequence(sequence); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/resources/application-mysql.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: 'jdbc:mysql://${DOCKER_IP}:3306/demo?useUnicode=yes&characterEncoding=UTF-8' 4 | username: root 5 | password: root 6 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | jpa: 3 | generate-ddl: true 4 | show-sql: true 5 | 6 | datasource: 7 | platform: h2 8 | url: "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false" 9 | username: sa 10 | password: 11 | 12 | h2: 13 | console: 14 | enabled: true 15 | logging: 16 | level: 17 | org.springframework.transaction: DEBUG 18 | org.springframework.orm.jpa: DEBUG 19 | -------------------------------------------------------------------------------- /src/test/java/com/example/MouseApplicationRestTest.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.google.common.collect.ImmutableMap; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | import org.springframework.test.web.servlet.MockMvc; 13 | 14 | import static org.assertj.core.api.BDDAssertions.then; 15 | import static org.hamcrest.CoreMatchers.endsWith; 16 | import static org.hamcrest.CoreMatchers.is; 17 | import static org.hamcrest.CoreMatchers.not; 18 | import static org.hamcrest.CoreMatchers.notNullValue; 19 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize; 20 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 22 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; 24 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 25 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 26 | 27 | @RunWith(SpringRunner.class) 28 | @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) 29 | @AutoConfigureMockMvc 30 | public class MouseApplicationRestTest { 31 | 32 | @Autowired 33 | private MockMvc mvc; 34 | 35 | @Autowired 36 | private MouseRepository mouseRepository; 37 | 38 | @Autowired 39 | private LatestMouseRepository latestMouseRepository; 40 | 41 | @Test 42 | public void should_put_resource_and_get_it_via_location() throws Exception { 43 | mvc.perform(put("/mice/mickey").content( 44 | new ObjectMapper().writeValueAsString(ImmutableMap.of( 45 | "name", "mickey" 46 | )) 47 | )) 48 | // .andDo(print()) 49 | .andExpect(status().isCreated()) 50 | .andExpect(header().string("Location", endsWith("/mice/mickey"))) 51 | .andDo((putMouse) -> { 52 | // follow the location header. 53 | mvc.perform(get(putMouse.getResponse().getHeader("Location"))) 54 | // .andDo(print()) 55 | .andExpect(status().isOk()) 56 | .andExpect(jsonPath("name", is("mickey"))) 57 | .andExpect(jsonPath("_id", notNullValue())); 58 | }) 59 | .andDo((putMouse) -> { 60 | mvc.perform(delete(putMouse.getResponse().getHeader("Location"))) 61 | // .andDo(print()) 62 | .andExpect(status().isNoContent()); 63 | }); 64 | } 65 | 66 | @Test 67 | public void should_update_age() throws Exception { 68 | mvc.perform(put("/mice/bernhard").content( 69 | new ObjectMapper().writeValueAsString(ImmutableMap.of( 70 | "name", "bernhard", 71 | "age", 10 72 | )) 73 | )) 74 | // .andDo(print()) 75 | .andDo(dnc -> { 76 | then(mouseRepository.findAll()).hasSize(1); 77 | then(latestMouseRepository.findAll()).hasSize(1); 78 | }) 79 | .andExpect(status().isCreated()) 80 | .andExpect(header().string("Location", endsWith("/mice/bernhard"))) 81 | .andDo((putMouse) -> { 82 | String jsonResponse = putMouse.getResponse().getContentAsString(); 83 | String oldId = new ObjectMapper().readTree(jsonResponse).get("_id").asText(); 84 | mvc.perform(put("/mice/bernhard").content(new ObjectMapper().writeValueAsString(ImmutableMap.of( 85 | "name", "bernhard", 86 | "age", 12 87 | )))) 88 | // .andDo(print()) 89 | .andExpect(status().isOk()) 90 | .andExpect(jsonPath("age", is(12))) 91 | .andExpect(jsonPath("_id", is(not(oldId)))); 92 | }); 93 | mvc.perform(get("/mice")) 94 | // .andDo(print()) 95 | .andExpect(status().isOk()) 96 | .andExpect(jsonPath("_embedded.mice", hasSize(1))); 97 | } 98 | 99 | 100 | } 101 | --------------------------------------------------------------------------------