diff --git a/.gitignore b/.gitignore
index 8c8680b24..f9e6e539d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,6 @@ target/
core/btm1.tlog
core/btm2.tlog
*.tlog
+*.log
+*.lck
+core/PutObjectStoreDirHere/
diff --git a/LICENSE b/LICENSE
index 8f71f43fe..5585b163c 100644
--- a/LICENSE
+++ b/LICENSE
@@ -175,18 +175,7 @@
END OF TERMS AND CONDITIONS
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright {yyyy} {name of copyright owner}
+ Copyright {2015-2024} {Mihalcea Vlad-Alexandru}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
diff --git a/MYSQL.md b/MYSQL.md
deleted file mode 100644
index 2e886f4da..000000000
--- a/MYSQL.md
+++ /dev/null
@@ -1,13 +0,0 @@
-* Install MySQL 5.6 (or later)
-* Create the database `high_performance_java_persistence`
- ```
- create database high_performance_java_persistence;
- ```
-* Create the user `mysql` and grant it the necessary privileges:
- ```
- create user 'mysql'@'localhost';
- SET PASSWORD for 'mysql'@'localhost' = PASSWORD('admin');
- GRANT ALL PRIVILEGES ON high_performance_java_persistence.* TO 'mysql'@'localhost';
- GRANT SELECT ON mysql.* TO 'mysql'@'localhost';
- FLUSH PRIVILEGES;
- ```
diff --git a/README.md b/README.md
index 010f3dedf..90a2c8408 100644
--- a/README.md
+++ b/README.md
@@ -1,46 +1,93 @@
# High-Performance Java Persistence
-The [High-Performance Java Persistence](https://leanpub.com/high-performance-java-persistence?utm_source=GitHub&utm_medium=banner&utm_campaign=hpjp) book code examples.
-
-
+The [High-Performance Java Persistence](https://vladmihalcea.com/books/high-performance-java-persistence?utm_source=GitHub&utm_medium=banner&utm_campaign=hpjp) book and video course code examples. I wrote [this article](https://vladmihalcea.com/high-performance-java-persistence-github-repository/) about this repository since it's one of the best way to test JDBC, JPA, Hibernate or even jOOQ code. Or, if you prefer videos, you can watch [this presentation on YouTube](https://www.youtube.com/watch?v=U8MoOe8uMYA).
+
+### Are you struggling with application performance issues?
+
+
+
-All examples require at least Java 1.8.
+Imagine having a tool that can automatically detect if you are using JPA and Hibernate properly. No more performance issues, no more having to spend countless hours trying to figure out why your application is barely crawling.
+
+Imagine discovering early during the development cycle that you are using suboptimal mappings and entity relationships or that you are missing performance-related settings.
+
+More, with Hypersistence Optimizer, you can detect all such issues during testing and make sure you don't deploy to production a change that will affect data access layer performance.
+
+[Hypersistence Optimizer](https://vladmihalcea.com/hypersistence-optimizer/?utm_source=GitHub&utm_medium=banner&utm_campaign=hpjp) is the tool you've been long waiting for!
+
+#### Training
+
+If you are interested in on-site training, I can offer you my [High-Performance Java Persistence training](https://vladmihalcea.com/trainings/?utm_source=GitHub&utm_medium=banner&utm_campaign=hpjp)
+which can be adapted to one, two or three days of sessions. For more details, check out [my website](https://vladmihalcea.com/trainings/?utm_source=GitHub&utm_medium=banner&utm_campaign=hpjp).
+
+#### Consulting
+
+If you want me to review your application and provide insight into how you can optimize it to run faster,
+then check out my [consulting page](https://vladmihalcea.com/consulting/?utm_source=GitHub&utm_medium=banner&utm_campaign=hpjp).
+
+#### High-Performance Java Persistence Video Courses
+
+If you want the fastest way to learn how to speed up a Java database application, then you should definitely enroll in [my High-Performance Java Persistence video courses](https://vladmihalcea.com/courses/?utm_source=GitHub&utm_medium=banner&utm_campaign=hpjp).
+
+#### High-Performance Java Persistence Book
+
+Or, if you prefer reading books, you are going to love my [High-Performance Java Persistence book](https://vladmihalcea.com/books/high-performance-java-persistence?utm_source=GitHub&utm_medium=banner&utm_campaign=hpjp) as well.
+
+
+
+
+
+
+
+
+
+## Java
+
+All examples require at least Java 17 because of the awesome [Text Blocks](https://openjdk.java.net/jeps/355) feature, which makes JPQL and SQL queries so much readable.
+
+## Maven
+
+You need to use Maven 3.6.2 or newer to build the project.
-**Javac compiler is required in order to run in in any IDE environment.
-Especially if you're using Eclipse, you must use the Oracle JDK compiler and not the Eclipse-based one which suffers from [this issue](https://bugs.eclipse.org/bugs/show_bug.cgi?id=434642).**
+## IntelliJ IDEA
-On InteliJ IDEA, the project runs just fine without any further requirements.
+On IntelliJ IDEA, the project runs just fine. You will have to make sure to select Java 17 or newer.
-However, on Eclipse it has been reported that you need to consider the following configurations (many thanks to [Urs Joss](https://github.com/ursjoss) for the hints):
+## Database setup
-1. Eclipse does not automatically treat the generated sources by jpamodelgen as source folders. You need to add a dependency on `hibernate-jpamodelgen` and use the `build-helper-maven-plugin` to source the folders with the generated sources.
-2. Secondly, the Maven eclipse plugin e2m seems to have an issue with some plugin configurations. Make sure you configure e2m to ignore the false positives issues (the project runs justs fine from a Maven command line).
-3. There’s an issue with Eclipse (or probably more specific ecj) to infer the types of parameters in case of method overloading with the methods `doInJpa`, `doInHibernate`, `doInJdbc`.
-Until [this Eclipse issue](https://bugs.eclipse.org/bugs/show_bug.cgi?id=434642) is fixed, you need to use the Oracle JDK to compile the project.
-If you can't change that, you need to rename those overloaded functions as explained by Urs Joss in [this specific commit](https://github.com/ursjoss/high-performance-java-persistence/commit/e975c1bb5c11d9557fcbc3fef88afaf67dc68a25).
+The project uses various database systems for integration testing, and you can configure the JDBC connection settings using the
+`DatasourceProvider` instances (e.g., `PostgreSQLDataSourceProvider`).
-The Unit Tests are run against HSQLDB, so no preliminary set-ups are required.
+By default, without configuring any database explicitly, HSQLDB is used for testing.
-The Integration Tests require some external configurations:
+However, since some integration tests are designed to work on specific relational databases, we will need to have those databases started prior to running those tests.
+
+Therefore, when running a DB-specific test, this GitHub repository will execute the following steps:
+
+1. First, the test will try to find whether there's a local RDBMS it can use to run the test.
+2. If no local database is found, the integration tests will use Testcontainers to bootstrap a Docker container
+with the required *Oracle*, *SQL Server*, *PostgreSQL*, *MySQL*, *MariaDB*, *YugabyteDB*, or *CockroachDB* instance on demand.
+
+> While you don't need to install any database manually on your local OS, this is recommended since your tests will run much faster than if they used Testcontainers.
+
+### Manual Database configuration
- PostgreSQL
- You should install PostgreSQL 9.5 (or later) and the password for the postgres user should be admin
+ You can install PostgreSQL, and the password for the `postgres` user should be `admin`.
- Now you need to create a `high_performance_java_persistence` database
- Open pgAdmin III and executed the following query:
-
- CREATE EXTENSION postgis;
- CREATE EXTENSION pgcrypto;
+ Now you need to create a `high_performance_java_persistence` database.
- Oracle
You need to download and install Oracle XE
- Set the sys password to admin
+ Set the `sys` password to `admin`
Connect to Oracle using the "sys as sysdba" user and create a new user:
+
+ alter session set "_ORACLE_SCRIPT"=true;
create user oracle identified by admin default tablespace users;
@@ -52,31 +99,36 @@ The Integration Tests require some external configurations:
ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
- For the Oracle JDBC driver, you have multiple alternatives.
-
- 1. You can follow the steps explained in [this article](http://docs.oracle.com/middleware/1213/core/MAVEN/config_maven_repo.htm#MAVEN9010) to set up the Oracle Maven Repository.
-
- 2. You can also download the Oracle JDBC Driver (ojdbc7_g.jar and ojdbc8.jar), which is not available in the Maven Central Repository.
- and install the ojdbc7_g.jar and ojdbc8.jar on your local Maven repository using the following command:
-
- $ mvn install:install-file -Dfile=ojdbc8.jar -DgroupId=com.oracle.jdbc -DartifactId=ojdbc8 -Dversion=12.2.0.1 -Dpackaging=jar
- $ mvn install:install-file -Dfile=ojdbc7_g.jar -DgroupId=com.oracle -DartifactId=ojdbc7_g -Dversion=12.1.0.1 -Dpackaging=jar
-
- The `com.oracle:ojdbc7_g` artifact is sued just by the jooq-oracle sub-module since there is some issue with the sql-maven-plugin Oracle dependency otherwise.
-
+ Open the `C:\app\${user.name}\product\21c\homes\OraDB21Home1\network\admin` folder where `${user.name}` is your current Windows username.
+
+ Locate the `tnsnames.ora` and `listener.ora` files and change the port from `1522` to `1521` if that's the case. If you made these modifications,
+ you need to restart the `OracleOraDB21Home1TNSListener` and `OracleServiceXE` Windows services.
+
- MySQL
- You should install MySQL 5.6 (or later) and the password for the mysql user should be admin.
+ You should install MySQL 8, and the password for the `mysql` user should be `admin`.
- Now you need to create a `high_performance_java_persistence` schema
+ Now, you need to create a `high_performance_java_persistence` schema
- Besides having all privileges on this schema, the user mysql also requires select persmission on `mysql.PROC`.
-
- Exact instructions can be found in [here](https://github.com/ursjoss/high-performance-java-persistence/blob/tb_mysql_instructions/MYSQL.md).
+ Besides having all privileges on this schema, the `mysql` user also requires select permission on `mysql.PROC`.
+
+ If you don't have a `mysql` user created at database installation time, you can create one as follows:
+
+ ````
+ CREATE USER 'mysql'@'localhost';
+
+ SET PASSWORD for 'mysql'@'localhost'='admin';
+
+ GRANT ALL PRIVILEGES ON high_performance_java_persistence.* TO 'mysql'@'localhost';
+
+ GRANT SELECT ON mysql.* TO 'mysql'@'localhost';
+
+ FLUSH PRIVILEGES;
+ ````
- SQL Server
- You should install SQL Server Express Edition with Tools Chose mixed mode authentication and set the sa user password to adm1n
+ You can install SQL Server Express Edition with Tools. Choose mixed mode authentication and set the `sa` user password to `adm1n`.
Open SQL Server Configuration Manager -> SQL Server Network Configuration and enable Named Pipes and TCP
@@ -85,10 +137,18 @@ The Integration Tests require some external configurations:
Open SQL Server Management Studio and create the `high_performance_java_persistence` database
-To build the project, don't use *install* or *package*. Instead, just compile test classes like this:
+## Maven
- mvn clean test-compile
+> To build the project, don't use *install* or *package*. Instead, just compile test classes like this:
+>
+> mvnw clean test-compile
+
+Or you can just run the `build.bat` or `build.sh` scripts which run the above Maven command.
-Then, just pick one test from the IDE and run it individually.
-If you run all tests (e.g. `mvn clean test`), the test suite will take way to long to complete since
-some performance tests require to run for long periods of time.
+Afterward, just pick one test from the IDE and run it individually.
+
+> Don't you run all tests at once (e.g. `mvn clean test`) because the test suite will take a very long time to complete.
+>
+> So, run the test you are interested in individually.
+
+Enjoy learning more about Java Persistence, Hibernate, and database systems!
diff --git a/build.bat b/build.bat
new file mode 100644
index 000000000..2c51e6af1
--- /dev/null
+++ b/build.bat
@@ -0,0 +1,12 @@
+@echo off
+
+pushd core
+call mvn -D skipTests clean install
+popd
+
+pushd jooq
+call mvn -D skipTests clean install
+call mvn test-compile
+popd
+
+goto:eof
\ No newline at end of file
diff --git a/build.sh b/build.sh
new file mode 100644
index 000000000..c06551626
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+
+call mvn -D skipTests clean install
\ No newline at end of file
diff --git a/core/pom.xml b/core/pom.xml
index 099107319..244f118c2 100644
--- a/core/pom.xml
+++ b/core/pom.xml
@@ -4,7 +4,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0%20http://maven.apache.org/xsd/maven-4.0.0.xsd">
- com.vladmihalcea.book
+ com.vladmihalcea
high-performance-java-persistence
1.0-SNAPSHOT
@@ -14,15 +14,70 @@
high-performance-java-persistence-core
+
+
+ com.blazebit
+ blaze-persistence-core-api-jakarta
+ ${blaze-persistence.version}
+
+
+ com.blazebit
+ blaze-persistence-core-impl-jakarta
+ ${blaze-persistence.version}
+
+
+
+ com.blazebit
+ blaze-persistence-jpa-criteria-api
+ ${blaze-persistence.version}
+
+
+
+ com.blazebit
+ blaze-persistence-jpa-criteria-impl
+ ${blaze-persistence.version}
+
+
+
+ com.blazebit
+ blaze-persistence-integration-hibernate-6.2
+ ${blaze-persistence.version}
+
+
+
+ com.blazebit
+ blaze-persistence-entity-view-api-jakarta
+ ${blaze-persistence.version}
+ compile
+
+
+
+ com.blazebit
+ blaze-persistence-entity-view-impl-jakarta
+ ${blaze-persistence.version}
+ runtime
+
+
+
+
+
+ net.steppschuh.markdowngenerator
+ markdowngenerator
+ 1.3.1.1
+
+
+
+
+
org.apache.maven.plugins
maven-jar-plugin
- 2.4
+ ${maven-jar-plugin}
@@ -39,12 +94,11 @@
-
-
true
- true
+ false
false
false
+ false
enhance
@@ -60,26 +114,6 @@
-
- org.bsc.maven
- maven-processor-plugin
- 2.0.5
-
-
- process
-
- process
-
- generate-sources
-
-
- org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor
-
-
-
-
-
-
diff --git a/core/spring-loadtime-weaving.bat b/core/spring-loadtime-weaving.bat
new file mode 100644
index 000000000..bb4aa7dd6
--- /dev/null
+++ b/core/spring-loadtime-weaving.bat
@@ -0,0 +1,5 @@
+@echo off
+
+call mvn -Dcmd.args="-javaagent:%M2_REPOSITORY%\org\springframework\spring-instrument\6.0.8\spring-instrument-6.0.8.jar" -Dtest=SpringDataJPARuntimeBytecodeEnhancementTest test
+
+goto:eof
\ No newline at end of file
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/Attachment.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/Attachment.java
deleted file mode 100644
index 205da229c..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/Attachment.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.forum;
-
-import javax.persistence.*;
-
-/**
- * @author Vlad Mihalcea
- */
-@Entity(name = "Attachment")
-@Table(name = "attachment")
-public class Attachment {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String name;
-
- @Enumerated
- @Column(name = "media_type")
- private MediaType mediaType;
-
- @Lob
- @Basic( fetch = FetchType.LAZY )
- private byte[] content;
-
- 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 MediaType getMediaType() {
- return mediaType;
- }
-
- public void setMediaType(MediaType mediaType) {
- this.mediaType = mediaType;
- }
-
- public byte[] getContent() {
- return content;
- }
-
- public void setContent(byte[] content) {
- this.content = content;
- }
-}
\ No newline at end of file
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/Post.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/Post.java
deleted file mode 100644
index f3d7b4219..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/Post.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.forum;
-
-import org.hibernate.annotations.LazyToOne;
-import org.hibernate.annotations.LazyToOneOption;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Vlad Mihalcea
- */
-@Entity
-@Table(name = "post")
-public class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- public Post() {
- }
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- @OneToOne(cascade = CascadeType.ALL, mappedBy = "post", fetch = FetchType.LAZY)
- @LazyToOne(LazyToOneOption.NO_PROXY)
- private PostDetails details;
-
- @ManyToMany
- @JoinTable(name = "post_tag",
- joinColumns = @JoinColumn(name = "post_id"),
- inverseJoinColumns = @JoinColumn(name = "tag_id")
- )
- private List tags = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public PostDetails getDetails() {
- return details;
- }
-
- public List getTags() {
- return tags;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
-
- public void addDetails(PostDetails details) {
- this.details = details;
- details.setPost(this);
- }
-
- public void removeDetails() {
- this.details.setPost(null);
- this.details = null;
- }
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/PostComment.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/PostComment.java
deleted file mode 100644
index f7ff86398..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/PostComment.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.forum;
-
-import javax.persistence.*;
-
-/**
- * @author Vlad Mihalcea
- */
-@Entity
-@Table(name = "post_comment")
-public class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public PostComment() {
- }
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/PostDetails.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/PostDetails.java
deleted file mode 100644
index 5bb236910..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/PostDetails.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.forum;
-
-import javax.persistence.*;
-import java.util.Date;
-
-/**
- * @author Vlad Mihalcea
- */
-@Entity
-@Table(name = "post_details")
-public class PostDetails {
-
- @Id
- @GeneratedValue
- private Long id;
-
- @Column(name = "created_on")
- private Date createdOn;
-
- @Column(name = "created_by")
- private String createdBy;
-
- public PostDetails() {
- createdOn = new Date();
- }
-
- @OneToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "post_id")
- private Post post;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public Date getCreatedOn() {
- return createdOn;
- }
-
- public void setCreatedOn(Date createdOn) {
- this.createdOn = createdOn;
- }
-
- public String getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/Tag.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/Tag.java
deleted file mode 100644
index edde8566d..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/Tag.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.forum;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-/**
- * @author Vlad Mihalcea
- */
-@Entity
-@Table(name = "tag")
-public class Tag {
-
- @Id
- private Long id;
-
- private String name;
-
- 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;
- }
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/AbstractArrayTypeDescriptor.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/AbstractArrayTypeDescriptor.java
deleted file mode 100644
index 287104f8e..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/AbstractArrayTypeDescriptor.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.array;
-
-import java.sql.Array;
-import java.sql.SQLException;
-import java.util.Arrays;
-import java.util.Properties;
-
-import org.hibernate.type.descriptor.WrapperOptions;
-import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
-import org.hibernate.type.descriptor.java.MutabilityPlan;
-import org.hibernate.type.descriptor.java.MutableMutabilityPlan;
-import org.hibernate.usertype.DynamicParameterizedType;
-
-/**
- * @author Vlad Mihalcea
- */
-public abstract class AbstractArrayTypeDescriptor
- extends AbstractTypeDescriptor implements DynamicParameterizedType {
-
- private Class arrayObjectClass;
-
- @Override
- public void setParameterValues(Properties parameters) {
- arrayObjectClass = ( (ParameterType) parameters.get( PARAMETER_TYPE ) ).getReturnedClass();
-
- }
-
- public AbstractArrayTypeDescriptor(Class arrayObjectClass) {
- super( arrayObjectClass, (MutabilityPlan) new MutableMutabilityPlan() {
- @Override
- protected T deepCopyNotNull(Object value) {
- return ArrayUtil.deepCopy( value );
- }
- } );
- this.arrayObjectClass = arrayObjectClass;
- }
-
- @Override
- public boolean areEqual(Object one, Object another) {
- if ( one == another ) {
- return true;
- }
- if ( one == null || another == null ) {
- return false;
- }
- return ArrayUtil.isEquals( one, another );
- }
-
- @Override
- public String toString(Object value) {
- return Arrays.deepToString((Object[]) value);
- }
-
- @Override
- public T fromString(String string) {
- return ArrayUtil.fromString(string, arrayObjectClass);
- }
-
- @SuppressWarnings({ "unchecked" })
- @Override
- public X unwrap(T value, Class type, WrapperOptions options) {
- return (X) ArrayUtil.wrapArray( value );
- }
-
- @Override
- public T wrap(X value, WrapperOptions options) {
- if( value instanceof Array ) {
- Array array = (Array) value;
- try {
- return ArrayUtil.unwrapArray( (Object[]) array.getArray(), arrayObjectClass );
- }
- catch (SQLException e) {
- throw new IllegalArgumentException( e );
- }
- }
- return (T) value;
- }
-
- protected abstract String getSqlArrayType();
-
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/ArraySqlTypeDescriptor.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/ArraySqlTypeDescriptor.java
deleted file mode 100644
index e30a43ae8..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/ArraySqlTypeDescriptor.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.array;
-
-import java.sql.CallableStatement;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-
-import org.hibernate.type.descriptor.ValueBinder;
-import org.hibernate.type.descriptor.ValueExtractor;
-import org.hibernate.type.descriptor.WrapperOptions;
-import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
-import org.hibernate.type.descriptor.sql.BasicBinder;
-import org.hibernate.type.descriptor.sql.BasicExtractor;
-import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
-
-/**
- * @author Vlad Mihalcea
- */
-public class ArraySqlTypeDescriptor implements SqlTypeDescriptor {
-
- public static final ArraySqlTypeDescriptor INSTANCE = new ArraySqlTypeDescriptor();
-
- @Override
- public int getSqlType() {
- return Types.ARRAY;
- }
-
- @Override
- public boolean canBeRemapped() {
- return true;
- }
-
- @Override
- public ValueBinder getBinder(JavaTypeDescriptor javaTypeDescriptor) {
- return new BasicBinder( javaTypeDescriptor, this) {
- @Override
- protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
- AbstractArrayTypeDescriptor abstractArrayTypeDescriptor = (AbstractArrayTypeDescriptor) javaTypeDescriptor;
- st.setArray( index, st.getConnection().createArrayOf(
- abstractArrayTypeDescriptor.getSqlArrayType(),
- abstractArrayTypeDescriptor.unwrap( value, Object[].class, options )
- ));
- }
-
- @Override
- protected void doBind(CallableStatement st, X value, String name, WrapperOptions options)
- throws SQLException {
- throw new UnsupportedOperationException( "Binding by name is not supported!" );
- }
- };
- }
-
- @Override
- public ValueExtractor getExtractor(final JavaTypeDescriptor javaTypeDescriptor) {
- return new BasicExtractor(javaTypeDescriptor, this) {
- @Override
- protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
- return javaTypeDescriptor.wrap(rs.getArray(name), options);
- }
-
- @Override
- protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException {
- return javaTypeDescriptor.wrap(statement.getArray(index), options);
- }
-
- @Override
- protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException {
- return javaTypeDescriptor.wrap(statement.getArray(name), options);
- }
- };
- }
-
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/ArrayUtil.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/ArrayUtil.java
deleted file mode 100644
index fdbedb1ce..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/ArrayUtil.java
+++ /dev/null
@@ -1,289 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.array;
-
-import java.lang.reflect.Array;
-import java.util.Arrays;
-
-/**
- * @author Vlad Mihalcea
- */
-public class ArrayUtil {
-
- public static T deepCopy(Object objectArray) {
- Class arrayClass = objectArray.getClass();
-
- if( boolean[].class.equals( arrayClass ) ) {
- boolean[] array = (boolean[]) objectArray;
- return (T) Arrays.copyOf( array, array.length);
- }
- else if( byte[].class.equals( arrayClass ) ) {
- byte[] array = (byte[]) objectArray;
- return (T) Arrays.copyOf(array, array.length);
- }
- else if( short[].class.equals( arrayClass ) ) {
- short[] array = (short[]) objectArray;
- return (T) Arrays.copyOf(array, array.length);
- }
- else if( int[].class.equals( arrayClass ) ) {
- int[] array = (int[]) objectArray;
- return (T) Arrays.copyOf(array, array.length);
- }
- else if( long[].class.equals( arrayClass ) ) {
- long[] array = (long[]) objectArray;
- return (T) Arrays.copyOf(array, array.length);
- }
- else if( float[].class.equals( arrayClass ) ) {
- float[] array = (float[]) objectArray;
- return (T) Arrays.copyOf(array, array.length);
- }
- else if( double[].class.equals( arrayClass ) ) {
- double[] array = (double[]) objectArray;
- return (T) Arrays.copyOf(array, array.length);
- }
- else if( char[].class.equals( arrayClass ) ) {
- char[] array = (char[]) objectArray;
- return (T) Arrays.copyOf(array, array.length);
- }
- else {
- Object[] array = (Object[]) objectArray;
- return (T) Arrays.copyOf(array, array.length);
- }
- }
-
- public static Object[] wrapArray(Object objectArray) {
- Class arrayClass = objectArray.getClass();
-
- if( boolean[].class.equals( arrayClass ) ) {
- boolean[] fromArray = (boolean[]) objectArray;
- Boolean[] array = new Boolean[ fromArray.length];
- for ( int i = 0; i < fromArray.length; i++ ) {
- array[i] = fromArray[i];
- }
- return array;
- }
- else if( byte[].class.equals( arrayClass ) ) {
- byte[] fromArray = (byte[]) objectArray;
- Byte[] array = new Byte[ fromArray.length];
- for ( int i = 0; i < fromArray.length; i++ ) {
- array[i] = fromArray[i];
- }
- return array;
- }
- else if( short[].class.equals( arrayClass ) ) {
- short[] fromArray = (short[]) objectArray;
- Short[] array = new Short[ fromArray.length];
- for ( int i = 0; i < fromArray.length; i++ ) {
- array[i] = fromArray[i];
- }
- return array;
- }
- else if( int[].class.equals( arrayClass ) ) {
- int[] fromArray = (int[]) objectArray;
- Integer[] array = new Integer[ fromArray.length];
- for ( int i = 0; i < fromArray.length; i++ ) {
- array[i] = fromArray[i];
- }
- return array;
- }
- else if( long[].class.equals( arrayClass ) ) {
- long[] fromArray = (long[]) objectArray;
- Long[] array = new Long[ fromArray.length];
- for ( int i = 0; i < fromArray.length; i++ ) {
- array[i] = fromArray[i];
- }
- return array;
- }
- else if( float[].class.equals( arrayClass ) ) {
- float[] fromArray = (float[]) objectArray;
- Float[] array = new Float[ fromArray.length];
- for ( int i = 0; i < fromArray.length; i++ ) {
- array[i] = fromArray[i];
- }
- return array;
- }
- else if( double[].class.equals( arrayClass ) ) {
- double[] fromArray = (double[]) objectArray;
- Double[] array = new Double[ fromArray.length];
- for ( int i = 0; i < fromArray.length; i++ ) {
- array[i] = fromArray[i];
- }
- return array;
- }
- else if( char[].class.equals( arrayClass ) ) {
- char[] fromArray = (char[]) objectArray;
- Character[] array = new Character[ fromArray.length];
- for ( int i = 0; i < fromArray.length; i++ ) {
- array[i] = fromArray[i];
- }
- return array;
- }
- else {
- return (Object[]) objectArray;
- }
- }
-
- public static T unwrapArray(Object[] objectArray, Class arrayClass) {
-
- if( boolean[].class.equals( arrayClass ) ) {
- boolean[] array = new boolean[objectArray.length];
- for ( int i = 0; i < objectArray.length; i++ ) {
- array[i] = objectArray[i] != null ? (Boolean) objectArray[i] : Boolean.FALSE;
- }
- return (T) array;
- }
- else if( byte[].class.equals( arrayClass ) ) {
- byte[] array = new byte[objectArray.length];
- for ( int i = 0; i < objectArray.length; i++ ) {
- array[i] = objectArray[i] != null ? (Byte) objectArray[i] : 0;
- }
- return (T) array;
- }
- else if( short[].class.equals( arrayClass ) ) {
- short[] array = new short[objectArray.length];
- for ( int i = 0; i < objectArray.length; i++ ) {
- array[i] = objectArray[i] != null ? (Short) objectArray[i] : 0;
- }
- return (T) array;
- }
- else if( int[].class.equals( arrayClass ) ) {
- int[] array = new int[objectArray.length];
- for ( int i = 0; i < objectArray.length; i++ ) {
- array[i] = objectArray[i] != null ? (Integer) objectArray[i] : 0;
- }
- return (T) array;
- }
- else if( long[].class.equals( arrayClass ) ) {
- long[] array = new long[objectArray.length];
- for ( int i = 0; i < objectArray.length; i++ ) {
- array[i] = objectArray[i] != null ? (Long) objectArray[i] : 0L;
- }
- return (T) array;
- }
- else if( float[].class.equals( arrayClass ) ) {
- float[] array = new float[objectArray.length];
- for ( int i = 0; i < objectArray.length; i++ ) {
- array[i] = objectArray[i] != null ? (Float) objectArray[i] : 0f;
- }
- return (T) array;
- }
- else if( double[].class.equals( arrayClass ) ) {
- double[] array = new double[objectArray.length];
- for ( int i = 0; i < objectArray.length; i++ ) {
- array[i] = objectArray[i] != null ? (Double) objectArray[i] : 0d;
- }
- return (T) array;
- }
- else if( char[].class.equals( arrayClass ) ) {
- char[] array = new char[objectArray.length];
- for ( int i = 0; i < objectArray.length; i++ ) {
- array[i] = objectArray[i] != null ? (Character) objectArray[i] : 0;
- }
- return (T) array;
- }
- else {
- return (T) objectArray;
- }
- }
-
- public static T fromString(String string, Class arrayClass) {
- String stringArray = string.replaceAll( "[\\[\\]]", "" );
- String[] tokens = stringArray.split( "," );
-
- int length = tokens.length;
-
- if( boolean[].class.equals( arrayClass ) ) {
- boolean[] array = new boolean[length];
- for ( int i = 0; i < tokens.length; i++ ) {
- array[i] = Boolean.valueOf( tokens[i] );
- }
- return (T) array;
- }
- else if( byte[].class.equals( arrayClass ) ) {
- byte[] array = new byte[length];
- for ( int i = 0; i < tokens.length; i++ ) {
- array[i] = Byte.valueOf( tokens[i] );
- }
- return (T) array;
- }
- else if( short[].class.equals( arrayClass ) ) {
- short[] array = new short[length];
- for ( int i = 0; i < tokens.length; i++ ) {
- array[i] = Short.valueOf( tokens[i] );
- }
- return (T) array;
- }
- else if( int[].class.equals( arrayClass ) ) {
- int[] array = new int[length];
- for ( int i = 0; i < tokens.length; i++ ) {
- array[i] = Integer.valueOf( tokens[i] );
- }
- return (T) array;
- }
- else if( long[].class.equals( arrayClass ) ) {
- long[] array = new long[length];
- for ( int i = 0; i < tokens.length; i++ ) {
- array[i] = Long.valueOf( tokens[i] );
- }
- return (T) array;
- }
- else if( float[].class.equals( arrayClass ) ) {
- float[] array = new float[length];
- for ( int i = 0; i < tokens.length; i++ ) {
- array[i] = Float.valueOf( tokens[i] );
- }
- return (T) array;
- }
- else if( double[].class.equals( arrayClass ) ) {
- double[] array = new double[length];
- for ( int i = 0; i < tokens.length; i++ ) {
- array[i] = Double.valueOf( tokens[i] );
- }
- return (T) array;
- }
- else if( char[].class.equals( arrayClass ) ) {
- char[] array = new char[length];
- for ( int i = 0; i < tokens.length; i++ ) {
- array[i] = tokens[i].length() > 0 ? tokens[i].charAt( 0 ) : Character.MIN_VALUE;
- }
- return (T) array;
- }
- else {
- return (T) tokens;
- }
- }
-
- public static boolean isEquals(Object firstArray, Object secondArray) {
- if(firstArray.getClass() != secondArray.getClass()) {
- return false;
- }
- Class arrayClass = firstArray.getClass();
-
- if( boolean[].class.equals( arrayClass ) ) {
- return Arrays.equals( (boolean[]) firstArray, (boolean[]) secondArray );
- }
- else if( byte[].class.equals( arrayClass ) ) {
- return Arrays.equals( (byte[]) firstArray, (byte[]) secondArray );
- }
- else if( short[].class.equals( arrayClass ) ) {
- return Arrays.equals( (short[]) firstArray, (short[]) secondArray );
- }
- else if( int[].class.equals( arrayClass ) ) {
- return Arrays.equals( (int[]) firstArray, (int[]) secondArray );
- }
- else if( long[].class.equals( arrayClass ) ) {
- return Arrays.equals( (long[]) firstArray, (long[]) secondArray );
- }
- else if( float[].class.equals( arrayClass ) ) {
- return Arrays.equals( (float[]) firstArray, (float[]) secondArray );
- }
- else if( double[].class.equals( arrayClass ) ) {
- return Arrays.equals( (double[]) firstArray, (double[]) secondArray );
- }
- else if( char[].class.equals( arrayClass ) ) {
- return Arrays.equals( (char[]) firstArray, (char[]) secondArray );
- }
- else {
- return Arrays.equals( (Object[]) firstArray, (Object[]) secondArray );
- }
- }
-
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/IntArrayType.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/IntArrayType.java
deleted file mode 100644
index 97ffdd87c..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/IntArrayType.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.array;
-
-import java.util.Properties;
-
-import org.hibernate.type.AbstractSingleColumnStandardBasicType;
-import org.hibernate.usertype.DynamicParameterizedType;
-
-/**
- * @author Vlad MIhalcea
- */
-public class IntArrayType
- extends AbstractSingleColumnStandardBasicType
- implements DynamicParameterizedType {
-
- public IntArrayType() {
- super( ArraySqlTypeDescriptor.INSTANCE, IntArrayTypeDescriptor.INSTANCE );
- }
-
- public String getName() {
- return "int-array";
- }
-
- @Override
- protected boolean registerUnderJavaType() {
- return true;
- }
-
- @Override
- public void setParameterValues(Properties parameters) {
- ((IntArrayTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters);
- }
-}
\ No newline at end of file
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/IntArrayTypeDescriptor.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/IntArrayTypeDescriptor.java
deleted file mode 100644
index 3cb147149..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/IntArrayTypeDescriptor.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.array;
-
-/**
- * @author Vlad Mihalcea
- */
-public class IntArrayTypeDescriptor
- extends AbstractArrayTypeDescriptor {
-
- public static final IntArrayTypeDescriptor INSTANCE = new IntArrayTypeDescriptor();
-
- public IntArrayTypeDescriptor() {
- super( int[].class );
- }
-
- @Override
- protected String getSqlArrayType() {
- return "integer";
- }
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/StringArrayType.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/StringArrayType.java
deleted file mode 100644
index d911ee799..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/StringArrayType.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.array;
-
-import java.util.Properties;
-
-import org.hibernate.type.AbstractSingleColumnStandardBasicType;
-import org.hibernate.usertype.DynamicParameterizedType;
-
-/**
- * @author Vlad MIhalcea
- */
-public class StringArrayType
- extends AbstractSingleColumnStandardBasicType
- implements DynamicParameterizedType {
-
- public StringArrayType() {
- super( ArraySqlTypeDescriptor.INSTANCE, StringArrayTypeDescriptor.INSTANCE );
- }
-
- public String getName() {
- return "string-array";
- }
-
- @Override
- protected boolean registerUnderJavaType() {
- return true;
- }
-
- @Override
- public void setParameterValues(Properties parameters) {
- ((StringArrayTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters);
- }
-}
\ No newline at end of file
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/StringArrayTypeDescriptor.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/StringArrayTypeDescriptor.java
deleted file mode 100644
index a20dfc4ae..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/array/StringArrayTypeDescriptor.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.array;
-
-/**
- * @author Vlad Mihalcea
- */
-public class StringArrayTypeDescriptor
- extends AbstractArrayTypeDescriptor {
-
- public static final StringArrayTypeDescriptor INSTANCE = new StringArrayTypeDescriptor();
-
- public StringArrayTypeDescriptor() {
- super( String[].class );
- }
-
- @Override
- protected String getSqlArrayType() {
- return "text";
- }
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/AbstractJsonSqlTypeDescriptor.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/AbstractJsonSqlTypeDescriptor.java
deleted file mode 100644
index 5336ef941..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/AbstractJsonSqlTypeDescriptor.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json;
-
-import org.hibernate.type.descriptor.ValueExtractor;
-import org.hibernate.type.descriptor.WrapperOptions;
-import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
-import org.hibernate.type.descriptor.sql.BasicExtractor;
-import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
-
-import java.sql.CallableStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-
-/**
- * @author Vlad Mihalcea
- */
-public abstract class AbstractJsonSqlTypeDescriptor implements SqlTypeDescriptor {
-
- @Override
- public int getSqlType() {
- return Types.OTHER;
- }
-
- @Override
- public boolean canBeRemapped() {
- return true;
- }
-
- @Override
- public ValueExtractor getExtractor(final JavaTypeDescriptor javaTypeDescriptor) {
- return new BasicExtractor(javaTypeDescriptor, this) {
- @Override
- protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
- return javaTypeDescriptor.wrap(rs.getObject(name), options);
- }
-
- @Override
- protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException {
- return javaTypeDescriptor.wrap(statement.getObject(index), options);
- }
-
- @Override
- protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException {
- return javaTypeDescriptor.wrap(statement.getObject(name), options);
- }
- };
- }
-
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JacksonUtil.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JacksonUtil.java
deleted file mode 100644
index 5204d3457..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JacksonUtil.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import java.io.IOException;
-
-/**
- * @author Vlad Mihalcea
- */
-public class JacksonUtil {
-
- public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
-
- public static T fromString(String string, Class clazz) {
- try {
- return OBJECT_MAPPER.readValue(string, clazz);
- } catch (IOException e) {
- throw new IllegalArgumentException("The given string value: " + string + " cannot be transformed to Json object");
- }
- }
-
- public static String toString(Object value) {
- try {
- return OBJECT_MAPPER.writeValueAsString(value);
- } catch (JsonProcessingException e) {
- throw new IllegalArgumentException("The given Json object value: " + value + " cannot be transformed to a String");
- }
- }
-
- public static JsonNode toJsonNode(String value) {
- try {
- return OBJECT_MAPPER.readTree(value);
- } catch (IOException e) {
- throw new IllegalArgumentException(e);
- }
- }
-
- public static T clone(T value) {
- return fromString(toString(value), (Class) value.getClass());
- }
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonBinarySqlTypeDescriptor.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonBinarySqlTypeDescriptor.java
deleted file mode 100644
index d45274559..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonBinarySqlTypeDescriptor.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import org.hibernate.type.descriptor.ValueBinder;
-import org.hibernate.type.descriptor.WrapperOptions;
-import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
-import org.hibernate.type.descriptor.sql.BasicBinder;
-
-import java.sql.CallableStatement;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-
-/**
- * @author Vlad Mihalcea
- */
-public class JsonBinarySqlTypeDescriptor extends AbstractJsonSqlTypeDescriptor {
-
- public static final JsonBinarySqlTypeDescriptor INSTANCE = new JsonBinarySqlTypeDescriptor();
-
- @Override
- public ValueBinder getBinder(final JavaTypeDescriptor javaTypeDescriptor) {
- return new BasicBinder(javaTypeDescriptor, this) {
- @Override
- protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
- st.setObject(index, javaTypeDescriptor.unwrap(value, JsonNode.class, options), getSqlType());
- }
-
- @Override
- protected void doBind(CallableStatement st, X value, String name, WrapperOptions options)
- throws SQLException {
- st.setObject(name, javaTypeDescriptor.unwrap(value, JsonNode.class, options), getSqlType());
- }
- };
- }
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonBinaryType.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonBinaryType.java
deleted file mode 100644
index ab644686e..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonBinaryType.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json;
-
-import org.hibernate.type.AbstractSingleColumnStandardBasicType;
-import org.hibernate.usertype.DynamicParameterizedType;
-
-import java.util.Properties;
-
-/**
- * Descriptor for a Json type.
- *
- * @author Vlad MIhalcea
- *
- */
-public class JsonBinaryType
- extends AbstractSingleColumnStandardBasicType implements DynamicParameterizedType {
-
- public JsonBinaryType() {
- super( JsonBinarySqlTypeDescriptor.INSTANCE, new JsonTypeDescriptor());
- }
-
- public String getName() {
- return "jsonb";
- }
-
- @Override
- public void setParameterValues(Properties parameters) {
- ((JsonTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters);
- }
-
-}
\ No newline at end of file
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonStringSqlTypeDescriptor.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonStringSqlTypeDescriptor.java
deleted file mode 100644
index 04bab85a5..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonStringSqlTypeDescriptor.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json;
-
-import org.hibernate.type.descriptor.ValueBinder;
-import org.hibernate.type.descriptor.WrapperOptions;
-import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
-import org.hibernate.type.descriptor.sql.BasicBinder;
-
-import java.sql.CallableStatement;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-
-/**
- * @author Vlad Mihalcea
- */
-public class JsonStringSqlTypeDescriptor extends AbstractJsonSqlTypeDescriptor {
-
- public static final JsonStringSqlTypeDescriptor INSTANCE = new JsonStringSqlTypeDescriptor();
-
- @Override
- public ValueBinder getBinder(final JavaTypeDescriptor javaTypeDescriptor) {
- return new BasicBinder(javaTypeDescriptor, this) {
- @Override
- protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
- st.setString(index, javaTypeDescriptor.unwrap(value, String.class, options));
- }
-
- @Override
- protected void doBind(CallableStatement st, X value, String name, WrapperOptions options)
- throws SQLException {
- st.setString(name, javaTypeDescriptor.unwrap(value, String.class, options));
- }
- };
- }
-
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonStringType.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonStringType.java
deleted file mode 100644
index 9b88a9e9c..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonStringType.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json;
-
-import org.hibernate.type.AbstractSingleColumnStandardBasicType;
-import org.hibernate.usertype.DynamicParameterizedType;
-
-import java.util.Properties;
-
-/**
- * @author Vlad MIhalcea
- */
-public class JsonStringType
- extends AbstractSingleColumnStandardBasicType implements DynamicParameterizedType {
-
- public JsonStringType() {
- super( JsonStringSqlTypeDescriptor.INSTANCE, new JsonTypeDescriptor() );
- }
-
- public String getName() {
- return "json";
- }
-
- @Override
- protected boolean registerUnderJavaType() {
- return true;
- }
-
- @Override
- public void setParameterValues(Properties parameters) {
- ((JsonTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters);
- }
-}
\ No newline at end of file
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonTypeDescriptor.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonTypeDescriptor.java
deleted file mode 100644
index 5501e16aa..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/JsonTypeDescriptor.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json;
-
-import org.hibernate.type.descriptor.WrapperOptions;
-import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
-import org.hibernate.type.descriptor.java.MutableMutabilityPlan;
-import org.hibernate.usertype.DynamicParameterizedType;
-
-import java.util.Properties;
-
-/**
- * @author Vlad Mihalcea
- */
-public class JsonTypeDescriptor
- extends AbstractTypeDescriptor implements DynamicParameterizedType {
-
- private Class> jsonObjectClass;
-
- @Override
- public void setParameterValues(Properties parameters) {
- jsonObjectClass = ( (ParameterType) parameters.get( PARAMETER_TYPE ) ).getReturnedClass();
-
- }
-
- public JsonTypeDescriptor() {
- super( Object.class, new MutableMutabilityPlan() {
- @Override
- protected Object deepCopyNotNull(Object value) {
- return JacksonUtil.clone(value);
- }
- });
- }
-
- @Override
- public boolean areEqual(Object one, Object another) {
- if ( one == another ) {
- return true;
- }
- if ( one == null || another == null ) {
- return false;
- }
- return JacksonUtil.toJsonNode(JacksonUtil.toString(one)).equals(
- JacksonUtil.toJsonNode(JacksonUtil.toString(another)));
- }
-
- @Override
- public String toString(Object value) {
- return JacksonUtil.toString(value);
- }
-
- @Override
- public Object fromString(String string) {
- return JacksonUtil.fromString(string, jsonObjectClass);
- }
-
- @SuppressWarnings({ "unchecked" })
- @Override
- public X unwrap(Object value, Class type, WrapperOptions options) {
- if ( value == null ) {
- return null;
- }
- if ( String.class.isAssignableFrom( type ) ) {
- return (X) toString(value);
- }
- if ( Object.class.isAssignableFrom( type ) ) {
- return (X) JacksonUtil.toJsonNode(toString(value));
- }
- throw unknownUnwrap( type );
- }
-
- @Override
- public Object wrap(X value, WrapperOptions options) {
- if ( value == null ) {
- return null;
- }
- return fromString(value.toString());
- }
-
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/BaseEntity.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/BaseEntity.java
deleted file mode 100644
index 4abe529e9..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/BaseEntity.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json.model;
-
-import javax.persistence.Id;
-import javax.persistence.MappedSuperclass;
-import javax.persistence.Version;
-
-import org.hibernate.annotations.TypeDef;
-import org.hibernate.annotations.TypeDefs;
-
-import com.vladmihalcea.book.hpjp.hibernate.type.array.IntArrayType;
-import com.vladmihalcea.book.hpjp.hibernate.type.array.StringArrayType;
-import com.vladmihalcea.book.hpjp.hibernate.type.json.JsonBinaryType;
-import com.vladmihalcea.book.hpjp.hibernate.type.json.JsonStringType;
-
-/**
- * @author Vlad Mihalcea
- */
-@TypeDefs({
- @TypeDef(name = "string-array", typeClass = StringArrayType.class),
- @TypeDef(name = "int-array", typeClass = IntArrayType.class),
- @TypeDef(name = "json", typeClass = JsonStringType.class),
- @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class),
-})
-@MappedSuperclass
-public class BaseEntity {
-
- @Id
- private Long id;
-
- @Version
- private Integer version;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Integer getVersion() {
- return version;
- }
-}
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Event.java b/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Event.java
deleted file mode 100644
index cf9ec5633..000000000
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Event.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json.model;
-
-import org.hibernate.annotations.Type;
-
-import javax.persistence.*;
-
-/**
- *
- * @author Vlad Mihalcea
- */
-@Entity(name = "Event")
-@Table(name = "event")
-public class Event extends BaseEntity {
-
- @Type(type = "jsonb")
- @Column(columnDefinition = "jsonb")
- @Basic( fetch = FetchType.LAZY )
- private Location location;
-
- public Location getLocation() {
- return location;
- }
-
- public void setLocation(Location location) {
- this.location = location;
- }
-}
\ No newline at end of file
diff --git a/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/Attachment.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/Attachment.java
new file mode 100644
index 000000000..9cd6b417b
--- /dev/null
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/Attachment.java
@@ -0,0 +1,60 @@
+package com.vladmihalcea.hpjp.hibernate.forum;
+
+import jakarta.persistence.*;
+
+/**
+ * @author Vlad Mihalcea
+ */
+@Entity(name = "Attachment")
+@Table(name = "attachment")
+public class Attachment {
+
+ @Id
+ private Long id;
+
+ private String name;
+
+ @Enumerated
+ @Column(name = "media_type")
+ private MediaType mediaType;
+
+ @Lob
+ @Basic(fetch = FetchType.LAZY)
+ private byte[] content;
+
+ public Long getId() {
+ return id;
+ }
+
+ public Attachment setId(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Attachment setName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public MediaType getMediaType() {
+ return mediaType;
+ }
+
+ public Attachment setMediaType(MediaType mediaType) {
+ this.mediaType = mediaType;
+ return this;
+ }
+
+ public byte[] getContent() {
+ return content;
+ }
+
+ public Attachment setContent(byte[] content) {
+ this.content = content;
+ return this;
+ }
+}
\ No newline at end of file
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/MediaType.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/MediaType.java
similarity index 89%
rename from core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/MediaType.java
rename to core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/MediaType.java
index ac86d3979..aa248d04f 100644
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/forum/MediaType.java
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/MediaType.java
@@ -1,4 +1,4 @@
-package com.vladmihalcea.book.hpjp.hibernate.forum;
+package com.vladmihalcea.hpjp.hibernate.forum;
/**
* @author Vlad Mihalcea
diff --git a/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/Post.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/Post.java
new file mode 100644
index 000000000..8232cdfca
--- /dev/null
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/Post.java
@@ -0,0 +1,104 @@
+package com.vladmihalcea.hpjp.hibernate.forum;
+
+import org.hibernate.annotations.LazyToOne;
+import org.hibernate.annotations.LazyToOneOption;
+
+import jakarta.persistence.*;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Vlad Mihalcea
+ */
+@Entity
+@Table(name = "post")
+public class Post {
+
+ @Id
+ private Long id;
+
+ private String title;
+
+ @OneToMany(
+ mappedBy = "post",
+ cascade = CascadeType.ALL,
+ orphanRemoval = true
+ )
+ private List comments = new ArrayList<>();
+
+ @OneToOne(
+ mappedBy = "post",
+ cascade = CascadeType.ALL,
+ fetch = FetchType.LAZY
+ )
+ @LazyToOne(LazyToOneOption.NO_PROXY)
+ private PostDetails details;
+
+ @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
+ @JoinTable(
+ name = "post_tag",
+ joinColumns = @JoinColumn(name = "post_id"),
+ inverseJoinColumns = @JoinColumn(name = "tag_id")
+ )
+ private List tags = new ArrayList<>();
+
+ 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 List getComments() {
+ return comments;
+ }
+
+ public PostDetails getDetails() {
+ return details;
+ }
+
+ public Post setDetails(PostDetails details) {
+ if (details == null) {
+ if (this.details != null) {
+ this.details.setPost(null);
+ }
+ }
+ else {
+ details.setPost(this);
+ }
+ this.details = details;
+ return this;
+ }
+
+ public List getTags() {
+ return tags;
+ }
+
+ public Post addComment(PostComment comment) {
+ comments.add(comment);
+ comment.setPost(this);
+ return this;
+ }
+
+ public Post removeComment(PostComment comment) {
+ comments.remove(comment);
+ comment.setPost(null);
+ return this;
+ }
+
+ public Post addTag(Tag tag) {
+ tags.add(tag);
+ return this;
+ }
+}
diff --git a/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/PostComment.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/PostComment.java
new file mode 100644
index 000000000..df4119b1b
--- /dev/null
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/PostComment.java
@@ -0,0 +1,46 @@
+package com.vladmihalcea.hpjp.hibernate.forum;
+
+import jakarta.persistence.*;
+
+/**
+ * @author Vlad Mihalcea
+ */
+@Entity
+@Table(name = "post_comment")
+public class PostComment {
+
+ @Id
+ private Long id;
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ private Post post;
+
+ private String review;
+
+ public Long getId() {
+ return id;
+ }
+
+ public PostComment setId(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public Post getPost() {
+ return post;
+ }
+
+ public PostComment setPost(Post post) {
+ this.post = post;
+ return this;
+ }
+
+ public String getReview() {
+ return review;
+ }
+
+ public PostComment setReview(String review) {
+ this.review = review;
+ return this;
+ }
+}
diff --git a/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/PostDetails.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/PostDetails.java
new file mode 100644
index 000000000..1230ce4aa
--- /dev/null
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/PostDetails.java
@@ -0,0 +1,63 @@
+package com.vladmihalcea.hpjp.hibernate.forum;
+
+import jakarta.persistence.*;
+import java.util.Date;
+
+/**
+ * @author Vlad Mihalcea
+ */
+@Entity
+@Table(name = "post_details")
+public class PostDetails {
+
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ @Column(name = "created_on")
+ private Date createdOn;
+
+ @Column(name = "created_by")
+ private String createdBy;
+
+ @OneToOne(fetch = FetchType.LAZY)
+ @MapsId
+ @JoinColumn(name = "id")
+ private Post post;
+
+ public Long getId() {
+ return id;
+ }
+
+ public PostDetails setId(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public Post getPost() {
+ return post;
+ }
+
+ public PostDetails setPost(Post post) {
+ this.post = post;
+ return this;
+ }
+
+ public Date getCreatedOn() {
+ return createdOn;
+ }
+
+ public PostDetails setCreatedOn(Date createdOn) {
+ this.createdOn = createdOn;
+ return this;
+ }
+
+ public String getCreatedBy() {
+ return createdBy;
+ }
+
+ public PostDetails setCreatedBy(String createdBy) {
+ this.createdBy = createdBy;
+ return this;
+ }
+}
diff --git a/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/Tag.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/Tag.java
new file mode 100644
index 000000000..557da1cbe
--- /dev/null
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/Tag.java
@@ -0,0 +1,36 @@
+package com.vladmihalcea.hpjp.hibernate.forum;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+
+/**
+ * @author Vlad Mihalcea
+ */
+@Entity
+@Table(name = "tag")
+public class Tag {
+
+ @Id
+ private Long id;
+
+ private String name;
+
+ public Long getId() {
+ return id;
+ }
+
+ public Tag setId(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Tag setName(String name) {
+ this.name = name;
+ return this;
+ }
+}
diff --git a/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/dto/PostDTO.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/dto/PostDTO.java
new file mode 100644
index 000000000..b85f9fe40
--- /dev/null
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/forum/dto/PostDTO.java
@@ -0,0 +1,24 @@
+package com.vladmihalcea.hpjp.hibernate.forum.dto;
+
+/**
+ * @author Vlad Mihalcea
+ */
+public class PostDTO {
+
+ private final Long id;
+
+ private final String title;
+
+ public PostDTO(Number id, String title) {
+ this.id = id.longValue();
+ this.title = title;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+}
diff --git a/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/BaseEntity.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/BaseEntity.java
new file mode 100644
index 000000000..b048055ed
--- /dev/null
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/BaseEntity.java
@@ -0,0 +1,30 @@
+package com.vladmihalcea.hpjp.hibernate.type.json.model;
+
+import jakarta.persistence.Id;
+import jakarta.persistence.MappedSuperclass;
+import jakarta.persistence.Version;
+
+/**
+ * @author Vlad Mihalcea
+ */
+@MappedSuperclass
+public class BaseEntity {
+
+ @Id
+ private Long id;
+
+ @Version
+ private Short version;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Short getVersion() {
+ return version;
+ }
+}
diff --git a/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Event.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Event.java
new file mode 100644
index 000000000..9c6deb1c3
--- /dev/null
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Event.java
@@ -0,0 +1,27 @@
+package com.vladmihalcea.hpjp.hibernate.type.json.model;
+
+import io.hypersistence.utils.hibernate.type.json.JsonBinaryType;
+import jakarta.persistence.*;
+import org.hibernate.annotations.Type;
+
+/**
+ *
+ * @author Vlad Mihalcea
+ */
+@Entity(name = "Event")
+@Table(name = "event")
+public class Event extends BaseEntity {
+
+ @Type(JsonBinaryType.class)
+ @Column(columnDefinition = "jsonb")
+ @Basic( fetch = FetchType.LAZY )
+ private Location location;
+
+ public Location getLocation() {
+ return location;
+ }
+
+ public void setLocation(Location location) {
+ this.location = location;
+ }
+}
\ No newline at end of file
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Location.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Location.java
similarity index 87%
rename from core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Location.java
rename to core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Location.java
index 716eb8064..5a5f70818 100644
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Location.java
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Location.java
@@ -1,4 +1,4 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json.model;
+package com.vladmihalcea.hpjp.hibernate.type.json.model;
import java.io.Serializable;
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Participant.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Participant.java
similarity index 77%
rename from core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Participant.java
rename to core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Participant.java
index 9c4c16a27..6dd6c2146 100644
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Participant.java
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Participant.java
@@ -1,9 +1,9 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json.model;
+package com.vladmihalcea.hpjp.hibernate.type.json.model;
+import io.hypersistence.utils.hibernate.type.json.JsonBinaryType;
+import jakarta.persistence.*;
import org.hibernate.annotations.Type;
-import javax.persistence.*;
-
/**
* @author Vlad Mihalcea
*/
@@ -11,7 +11,7 @@
@Table(name = "participant")
public class Participant extends BaseEntity {
- @Type(type = "jsonb")
+ @Type(JsonBinaryType.class)
@Column(columnDefinition = "jsonb")
@Basic(fetch = FetchType.LAZY)
private Ticket ticket;
diff --git a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Ticket.java b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Ticket.java
similarity index 89%
rename from core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Ticket.java
rename to core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Ticket.java
index 1b6d8da71..ab03e7e50 100644
--- a/core/src/main/java/com/vladmihalcea/book/hpjp/hibernate/type/json/model/Ticket.java
+++ b/core/src/main/java/com/vladmihalcea/hpjp/hibernate/type/json/model/Ticket.java
@@ -1,4 +1,4 @@
-package com.vladmihalcea.book.hpjp.hibernate.type.json.model;
+package com.vladmihalcea.hpjp.hibernate.type.json.model;
import java.io.Serializable;
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/AllAssociationTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/AllAssociationTest.java
deleted file mode 100644
index 2da567342..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/AllAssociationTest.java
+++ /dev/null
@@ -1,286 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.Criteria;
-import org.hibernate.FetchMode;
-import org.hibernate.Session;
-import org.hibernate.criterion.Restrictions;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Vlad Mihalcea
- */
-public class AllAssociationTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostDetails.class,
- PostComment.class,
- Tag.class
- };
- }
-
- @Test
- public void test() {
- doInJPA(entityManager -> {
- Post post = new Post(1L);
- post.title = "Postit";
-
- PostComment comment1 = new PostComment();
- comment1.id = 1L;
- comment1.review = "Good";
-
- PostComment comment2 = new PostComment();
- comment2.id = 2L;
- comment2.review = "Excellent";
-
- post.addComment(comment1);
- post.addComment(comment2);
- entityManager.persist(post);
-
- Session session = entityManager.unwrap(Session.class);
- Criteria criteria = session.createCriteria(Post.class)
- .add(Restrictions.eq("title", "post"));
- LOGGER.info("Criteria: {}", criteria);
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("No alias");
- Session session = entityManager.unwrap(Session.class);
- List posts = session
- .createCriteria(Post.class)
- .setFetchMode("comments", FetchMode.JOIN)
- .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
- .add(Restrictions.eq("title", "Postit"))
- .list();
- assertEquals(1, posts.size());
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("With alias");
- Session session = entityManager.unwrap(Session.class);
- List posts = session
- .createCriteria(Post.class, "post")
- .setFetchMode("post.comments", FetchMode.JOIN)
- .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
- .add(Restrictions.eq("post.title", "Postit"))
- .list();
- assertEquals(1, posts.size());
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("With alias");
- Session session = entityManager.unwrap(Session.class);
- List posts = session
- .createCriteria(Post.class, "post")
- .setFetchMode("post.comments", FetchMode.JOIN)
- .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
- .add(Restrictions.eq("post.title", "Postit"))
- .list();
- assertEquals(1, posts.size());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- @OneToOne(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true, fetch = FetchType.LAZY)
- private PostDetails details;
-
- @ManyToMany
- @JoinTable(name = "post_tag",
- joinColumns = @JoinColumn(name = "post_id"),
- inverseJoinColumns = @JoinColumn(name = "tag_id")
- )
- private List tags = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public PostDetails getDetails() {
- return details;
- }
-
- public List getTags() {
- return tags;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
-
- public void addDetails(PostDetails details) {
- this.details = details;
- details.setPost(this);
- }
-
- public void removeDetails() {
- this.details.setPost(null);
- this.details = null;
- }
- }
-
- @Entity(name = "PostDetails")
- @Table(name = "post_details")
- public static class PostDetails {
-
- @Id
- private Long id;
-
- @Column(name = "created_on")
- private Date createdOn;
-
- @Column(name = "created_by")
- private String createdBy;
-
- public PostDetails() {
- createdOn = new Date();
- }
-
- @OneToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "id")
- @MapsId
- private Post post;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public Date getCreatedOn() {
- return createdOn;
- }
-
- public void setCreatedOn(Date createdOn) {
- this.createdOn = createdOn;
- }
-
- public String getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne
- private Post post;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-
- @Entity(name = "Tag")
- @Table(name = "tag")
- public static class Tag {
-
- @Id
- private Long id;
-
- private String name;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyAsOneToManyOrderColumnTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyAsOneToManyOrderColumnTest.java
deleted file mode 100644
index 6db73bc0b..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyAsOneToManyOrderColumnTest.java
+++ /dev/null
@@ -1,299 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * @author Vlad Mihalcea
- */
-public class BidirectionalManyAsOneToManyOrderColumnTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- Tag.class,
- PostTag.class
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- entityManager.persist(tag1);
- entityManager.persist(tag2);
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.flush();
-
- LOGGER.info("Remove");
- post1.removeTag(tag1);
- });
- }
-
- @Test
- public void testShuffle() {
- final Long postId = doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- entityManager.persist(tag1);
- entityManager.persist(tag2);
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.flush();
-
- return post1.getId();
- });
- doInJPA(entityManager -> {
- LOGGER.info("Shuffle");
- Post post1 = entityManager.find(Post.class, postId);
- post1.getTags().sort((postTag1, postTag2) ->
- postTag2.getId().getTagId().compareTo(postTag1.getId().getTagId())
- );
- });
- }
-
- @Entity(name = "Post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
- @OrderColumn(name = "entry")
- private List tags = new ArrayList<>();
-
- public Post() {
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- public Long getId() {
- return id;
- }
-
- public List getTags() {
- return tags;
- }
-
- public void addTag(Tag tag) {
- PostTag postTag = new PostTag(this, tag);
- tags.add(postTag);
- tag.getPosts().add(postTag);
- }
-
- public void removeTag(Tag tag) {
- for (Iterator iterator = tags.iterator(); iterator.hasNext(); ) {
- PostTag postTag = iterator.next();
- if (postTag.getPost().equals(this) &&
- postTag.getTag().equals(tag)) {
- iterator.remove();
- postTag.getTag().getPosts().remove(postTag);
- postTag.setPost(null);
- postTag.setTag(null);
- break;
- }
- }
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Post post = (Post) o;
- return Objects.equals(title, post.title);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(title);
- }
- }
-
- @Embeddable
- public static class PostTagId implements Serializable {
-
- private Long postId;
-
- private Long tagId;
-
- public PostTagId() {
- }
-
- public PostTagId(Long postId, Long tagId) {
- this.postId = postId;
- this.tagId = tagId;
- }
-
- public Long getPostId() {
- return postId;
- }
-
- public Long getTagId() {
- return tagId;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- PostTagId that = (PostTagId) o;
- return Objects.equals(postId, that.postId) &&
- Objects.equals(tagId, that.tagId);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(postId, tagId);
- }
- }
-
- @Entity(name = "PostTag")
- public static class PostTag {
-
- @EmbeddedId
- private PostTagId id;
-
- @ManyToOne
- @MapsId("postId")
- private Post post;
-
- @ManyToOne
- @MapsId("tagId")
- private Tag tag;
-
- public PostTag() {
- }
-
- 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 Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public Tag getTag() {
- return tag;
- }
-
- public void setTag(Tag tag) {
- this.tag = tag;
- }
-
- @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(post, that.post) &&
- Objects.equals(tag, that.tag);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(post, tag);
- }
- }
-
- @Entity(name = "Tag")
- public static class Tag {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String name;
-
- @OneToMany(mappedBy = "tag", cascade = CascadeType.ALL, orphanRemoval = true)
- private List posts = new ArrayList<>();
-
- public Tag() {
- }
-
- public Tag(String name) {
- this.name = name;
- }
-
- 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 List getPosts() {
- return posts;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Tag tag = (Tag) o;
- return Objects.equals(name, tag.name);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(name);
- }
- }
-
-
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyAsOneToManyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyAsOneToManyTest.java
deleted file mode 100644
index 54125a2b8..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyAsOneToManyTest.java
+++ /dev/null
@@ -1,295 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * @author Vlad Mihalcea
- */
-public class BidirectionalManyAsOneToManyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- Tag.class,
- PostTag.class
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- entityManager.persist(tag1);
- entityManager.persist(tag2);
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.flush();
-
- LOGGER.info("Remove");
- post1.removeTag(tag1);
- });
- }
-
- @Test
- public void testShuffle() {
- final Long postId = doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- entityManager.persist(tag1);
- entityManager.persist(tag2);
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.flush();
-
- return post1.getId();
- });
- doInJPA(entityManager -> {
- LOGGER.info("Shuffle");
- Post post1 = entityManager.find(Post.class, postId);
- post1.getTags().sort((postTag1, postTag2) ->
- postTag2.getId().getTagId().compareTo(postTag1.getId().getTagId())
- );
- });
- }
-
- @Entity(name = "Post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
- private List tags = new ArrayList<>();
-
- public Post() {
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- public Long getId() {
- return id;
- }
-
- public List getTags() {
- return tags;
- }
-
- public void addTag(Tag tag) {
- PostTag postTag = new PostTag(this, tag);
- tags.add(postTag);
- tag.getPosts().add(postTag);
- }
-
- public void removeTag(Tag tag) {
- for (Iterator iterator = tags.iterator(); iterator.hasNext(); ) {
- PostTag postTag = iterator.next();
- if (postTag.getPost().equals(this) &&
- postTag.getTag().equals(tag)) {
- iterator.remove();
- postTag.getTag().getPosts().remove(postTag);
- postTag.setPost(null);
- postTag.setTag(null);
- }
- }
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Post post = (Post) o;
- return Objects.equals(title, post.title);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(title);
- }
- }
-
- @Embeddable
- public static class PostTagId implements Serializable {
-
- private Long postId;
-
- private Long tagId;
-
- public PostTagId() {}
-
- public PostTagId(Long postId, Long tagId) {
- this.postId = postId;
- this.tagId = tagId;
- }
-
- public Long getPostId() {
- return postId;
- }
-
- public Long getTagId() {
- return tagId;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- PostTagId that = (PostTagId) o;
- return Objects.equals(postId, that.postId) &&
- Objects.equals(tagId, that.tagId);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(postId, tagId);
- }
- }
-
- @Entity(name = "PostTag") @Table(name = "post_tag")
- public static class PostTag {
-
- @EmbeddedId
- private PostTagId id;
-
- @ManyToOne
- @MapsId("postId")
- private Post post;
-
- @ManyToOne
- @MapsId("tagId")
- private Tag tag;
-
- private PostTag() {}
-
- 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 Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public Tag getTag() {
- return tag;
- }
-
- public void setTag(Tag tag) {
- this.tag = tag;
- }
-
- @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(post, that.post) &&
- Objects.equals(tag, that.tag);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(post, tag);
- }
- }
-
- @Entity(name = "Tag")
- public static class Tag {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String name;
-
- @OneToMany(mappedBy = "tag", cascade = CascadeType.ALL, orphanRemoval = true)
- private List posts = new ArrayList<>();
-
- public Tag() {
- }
-
- public Tag(String name) {
- this.name = name;
- }
-
- 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 List getPosts() {
- return posts;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Tag tag = (Tag) o;
- return Objects.equals(name, tag.name);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(name);
- }
- }
-
-
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyAsOneToManyWithoutEmbeddedIdTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyAsOneToManyWithoutEmbeddedIdTest.java
deleted file mode 100644
index 3d059bd5d..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyAsOneToManyWithoutEmbeddedIdTest.java
+++ /dev/null
@@ -1,255 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * @author Vlad Mihalcea
- */
-public class BidirectionalManyAsOneToManyWithoutEmbeddedIdTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- Tag.class,
- PostTag.class
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- entityManager.persist(tag1);
- entityManager.persist(tag2);
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.flush();
-
- LOGGER.info("Remove");
- post1.removeTag(tag1);
- });
- }
-
- @Test
- public void testShuffle() {
- final Long postId = doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- tag1.setId(1L);
- Tag tag2 = new Tag("Hibernate");
- tag2.setId(2L);
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- entityManager.persist(tag1);
- entityManager.persist(tag2);
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.flush();
-
- return post1.getId();
- });
- doInJPA(entityManager -> {
- LOGGER.info("Shuffle");
- Post post1 = entityManager.find(Post.class, postId);
- Tag tag1 = entityManager.find(Tag.class, 1L);
-
- PostTag postTag = entityManager.find(PostTag.class, new PostTag(post1, tag1));
-
- post1.getTags().sort((postTag1, postTag2) ->
- postTag2.getTag().getId().compareTo(postTag1.getTag().getId())
- );
- });
- }
-
- @Entity(name = "Post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
- private List tags = new ArrayList<>();
-
- public Post() {
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- public Long getId() {
- return id;
- }
-
- public List getTags() {
- return tags;
- }
-
- public void addTag(Tag tag) {
- PostTag postTag = new PostTag(this, tag);
- tags.add(postTag);
- tag.getPosts().add(postTag);
- }
-
- public void removeTag(Tag tag) {
- for (Iterator iterator = tags.iterator(); iterator.hasNext(); ) {
- PostTag postTag = iterator.next();
- if (postTag.getPost().equals(this) &&
- postTag.getTag().equals(tag)) {
- iterator.remove();
- postTag.getTag().getPosts().remove(postTag);
- postTag.setPost(null);
- postTag.setTag(null);
- }
- }
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Post post = (Post) o;
- return Objects.equals(title, post.title);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(title);
- }
- }
-
- @Entity(name = "PostTag") @Table(name = "post_tag")
- public static class PostTag implements Serializable {
-
- @Id
- @ManyToOne
- private Post post;
-
- @Id
- @ManyToOne
- private Tag tag;
-
- private PostTag() {}
-
- public PostTag(Post post, Tag tag) {
- this.post = post;
- this.tag = tag;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public Tag getTag() {
- return tag;
- }
-
- public void setTag(Tag tag) {
- this.tag = tag;
- }
-
- @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(post, that.post) &&
- Objects.equals(tag, that.tag);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(post, tag);
- }
- }
-
- @Entity(name = "Tag")
- public static class Tag {
-
- @Id
- private Long id;
-
- private String name;
-
- @OneToMany(mappedBy = "tag", cascade = CascadeType.ALL, orphanRemoval = true)
- private List posts = new ArrayList<>();
-
- public Tag() {
- }
-
- public Tag(String name) {
- this.name = name;
- }
-
- 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 List getPosts() {
- return posts;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Tag tag = (Tag) o;
- return Objects.equals(name, tag.name);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(name);
- }
- }
-
-
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyToManyListTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyToManyListTest.java
deleted file mode 100644
index def489e1e..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyToManyListTest.java
+++ /dev/null
@@ -1,239 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-import java.util.Set;
-import javax.persistence.CascadeType;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.ManyToMany;
-import javax.persistence.Table;
-
-import org.hibernate.annotations.NaturalId;
-
-import org.junit.Test;
-
-import com.vladmihalcea.book.hpjp.util.AbstractMySQLIntegrationTest;
-
-/**
- * @author Vlad Mihalcea
- */
-public class BidirectionalManyToManyListTest extends AbstractMySQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- Tag.class
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- entityManager.flush();
-
- post1.removeTag(tag1);
- });
- }
-
- @Test
- public void testRemove() {
- final Long postId = doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- return post1.id;
- });
- doInJPA(entityManager -> {
- LOGGER.info("Remove");
- Post post1 = entityManager.find(Post.class, postId);
-
- entityManager.remove(post1);
- });
- }
-
- @Test
- public void testShuffle() {
- final Long postId = doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- return post1.id;
- });
- doInJPA(entityManager -> {
- LOGGER.info("Shuffle");
- Tag tag1 = new Tag("Java");
- Post post1 = entityManager
- .createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.tags " +
- "where p.id = :id", Post.class)
- .setParameter( "id", postId )
- .getSingleResult();
-
- post1.removeTag(tag1);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(String title) {
- this.title = title;
- }
-
- @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE})
- @JoinTable(name = "post_tag",
- joinColumns = @JoinColumn(name = "post_id"),
- inverseJoinColumns = @JoinColumn(name = "tag_id")
- )
- private List tags = new ArrayList<>();
-
- 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 List getTags() {
- return tags;
- }
-
- public void addTag(Tag tag) {
- tags.add(tag);
- tag.getPosts().add(this);
- }
-
- public void removeTag(Tag tag) {
- tags.remove(tag);
- tag.getPosts().remove(this);
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof Post)) return false;
- return id != null && id.equals(((Post) o).id);
- }
-
- @Override
- public int hashCode() {
- return 31;
- }
- }
-
- @Entity(name = "Tag")
- @Table(name = "tag")
- public static class Tag {
-
- @Id
- @GeneratedValue
- private Long id;
-
- @NaturalId
- private String name;
-
- @ManyToMany(mappedBy = "tags")
- private List posts = new ArrayList<>();
-
- public Tag() {}
-
- public Tag(String name) {
- this.name = name;
- }
-
- 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 List getPosts() {
- return posts;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Tag tag = (Tag) o;
- return Objects.equals(name, tag.name);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(name);
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyToManySetTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyToManySetTest.java
deleted file mode 100644
index f56cd91ae..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyToManySetTest.java
+++ /dev/null
@@ -1,229 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractMySQLIntegrationTest;
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.*;
-
-import org.hibernate.annotations.NaturalId;
-
-/**
- * @author Vlad Mihalcea
- */
-public class BidirectionalManyToManySetTest extends AbstractMySQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- Tag.class
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- entityManager.flush();
-
- post1.removeTag(tag1);
- });
- }
-
- @Test
- public void testRemove() {
- final Long postId = doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- return post1.id;
- });
- doInJPA(entityManager -> {
- LOGGER.info("Remove");
- Post post1 = entityManager.find(Post.class, postId);
-
- entityManager.remove(post1);
- });
- }
-
- @Test
- public void testShuffle() {
- final Long postId = doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- post1.addTag(tag1);
- post1.addTag(tag2);
-
- post2.addTag(tag1);
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- return post1.id;
- });
- doInJPA(entityManager -> {
- LOGGER.info("Shuffle");
- Tag tag1 = new Tag("Java");
- Post post1 = entityManager
- .createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.tags " +
- "where p.id = :id", Post.class)
- .setParameter( "id", postId )
- .getSingleResult();
-
- post1.removeTag(tag1);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(String title) {
- this.title = title;
- }
-
- @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE})
- @JoinTable(name = "post_tag",
- joinColumns = @JoinColumn(name = "post_id"),
- inverseJoinColumns = @JoinColumn(name = "tag_id")
- )
- private Set tags = new HashSet<>();
-
- 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 Set getTags() {
- return tags;
- }
-
- public void addTag(Tag tag) {
- tags.add(tag);
- tag.getPosts().add(this);
- }
-
- public void removeTag(Tag tag) {
- tags.remove(tag);
- tag.getPosts().remove(this);
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof Post)) return false;
- return id != null && id.equals(((Post) o).id);
- }
-
- @Override
- public int hashCode() {
- return 31;
- }
- }
-
- @Entity(name = "Tag")
- @Table(name = "tag")
- public static class Tag {
-
- @Id
- @GeneratedValue
- private Long id;
-
- @NaturalId
- private String name;
-
- @ManyToMany(mappedBy = "tags")
- private Set posts = new HashSet<>();
-
- public Tag() {}
-
- public Tag(String name) {
- this.name = name;
- }
-
- 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 Set getPosts() {
- return posts;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Tag tag = (Tag) o;
- return Objects.equals(name, tag.name);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(name);
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalOneToManyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalOneToManyTest.java
deleted file mode 100644
index 15dc607f2..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalOneToManyTest.java
+++ /dev/null
@@ -1,154 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Vlad Mihalcea
- */
-public class BidirectionalOneToManyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post = new Post("First post");
-
- post.addComment(
- new PostComment("My first review")
- );
- post.addComment(
- new PostComment("My second review")
- );
- post.addComment(
- new PostComment( "My third review")
- );
-
- entityManager.persist(post);
- });
- doInJPA(entityManager -> {
-
- Post post = entityManager.find( Post.class, 1L );
- PostComment comment1 = post.getComments().get( 0 );
-
- post.removeComment(comment1);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- public Post() {}
-
- public Post(String title) {
- this.title = title;
- }
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
-
- public void removeComment(PostComment comment) {
- comments.remove(comment);
- comment.setPost(null);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String review;
-
- @ManyToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "post_id")
- private Post post;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof PostComment )) return false;
- return id != null && id.equals(((PostComment) o).id);
- }
- @Override
- public int hashCode() {
- return 31;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalOneToOneLazyNoProxyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalOneToOneLazyNoProxyTest.java
deleted file mode 100644
index 8e72267ed..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalOneToOneLazyNoProxyTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import java.util.List;
-
-import org.junit.Test;
-
-import com.vladmihalcea.book.hpjp.hibernate.forum.Post;
-import com.vladmihalcea.book.hpjp.hibernate.forum.PostComment;
-import com.vladmihalcea.book.hpjp.hibernate.forum.PostDetails;
-import com.vladmihalcea.book.hpjp.hibernate.forum.Tag;
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-
-import static junit.framework.TestCase.assertNull;
-import static junit.framework.TestCase.fail;
-import static org.junit.Assert.assertNotNull;
-
-/**
- * @author Vlad Mihalcea
- */
-public class BidirectionalOneToOneLazyNoProxyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostDetails.class,
- PostComment.class,
- Tag.class
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post1 = new Post("First post");
- post1.setId( 1L );
-
- PostDetails details1 = new PostDetails();
- details1.setCreatedBy( "John Doe" );
- post1.addDetails(details1);
-
- Post post2 = new Post("Second post");
- post2.setId( 2L );
-
- entityManager.persist(post1);
- entityManager.persist(post2);
- });
- List posts = doInJPA(entityManager -> {
- return entityManager.createQuery(
- "select p " +
- "from Post p ", Post.class)
- .getResultList();
- });
-
- try {
- assertNotNull(posts.get( 0 ).getDetails());
- fail("Should throw LazyInitializationException");
- }
- catch (Exception expected) {
- LOGGER.info( "The @OneToOne association was fetched lazily" );
- }
-
- doInJPA(entityManager -> {
- Post post = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "where p.id = :postId", Post.class)
- .setParameter( "postId", 2L )
- .getSingleResult();
-
- LOGGER.info( "Fetched Post" );
- assertNull(post.getDetails());
- });
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/ElementCollectionTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/ElementCollectionTest.java
deleted file mode 100644
index 515b33197..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/ElementCollectionTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractMySQLIntegrationTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Vlad Mihalcea
- */
-public class ElementCollectionTest extends AbstractMySQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post = new Post("First post");
-
- post.getComments().add("My first review");
- post.getComments().add("My second review");
- post.getComments().add("My third review");
-
- entityManager.persist(post);
- entityManager.flush();
-
- post.getComments().remove(2);
- entityManager.flush();
-
- LOGGER.info("Remove head");
- post.getComments().remove(0);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(String title) {
- this.title = title;
- }
-
- @ElementCollection
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/IntroAssociationTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/IntroAssociationTest.java
deleted file mode 100644
index 5bff09407..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/IntroAssociationTest.java
+++ /dev/null
@@ -1,286 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.Criteria;
-import org.hibernate.FetchMode;
-import org.hibernate.Session;
-import org.hibernate.criterion.Restrictions;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Vlad Mihalcea
- */
-public class IntroAssociationTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostDetails.class,
- PostComment.class,
- Tag.class
- };
- }
-
- @Test
- public void test() {
- doInJPA(entityManager -> {
- Post post = new Post(1L);
- post.title = "Postit";
-
- PostComment comment1 = new PostComment();
- comment1.id = 1L;
- comment1.review = "Good";
-
- PostComment comment2 = new PostComment();
- comment2.id = 2L;
- comment2.review = "Excellent";
-
- post.addComment(comment1);
- post.addComment(comment2);
- entityManager.persist(post);
-
- Session session = entityManager.unwrap(Session.class);
- Criteria criteria = session.createCriteria(Post.class)
- .add(Restrictions.eq("title", "post"));
- LOGGER.info("Criteria: {}", criteria);
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("No alias");
- Session session = entityManager.unwrap(Session.class);
- List posts = session
- .createCriteria(Post.class)
- .setFetchMode("comments", FetchMode.JOIN)
- .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
- .add(Restrictions.eq("title", "Postit"))
- .list();
- assertEquals(1, posts.size());
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("With alias");
- Session session = entityManager.unwrap(Session.class);
- List posts = session
- .createCriteria(Post.class, "post")
- .setFetchMode("post.comments", FetchMode.JOIN)
- .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
- .add(Restrictions.eq("post.title", "Postit"))
- .list();
- assertEquals(1, posts.size());
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("With alias");
- Session session = entityManager.unwrap(Session.class);
- List posts = session
- .createCriteria(Post.class, "post")
- .setFetchMode("post.comments", FetchMode.JOIN)
- .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
- .add(Restrictions.eq("post.title", "Postit"))
- .list();
- assertEquals(1, posts.size());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- @OneToOne(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true, fetch = FetchType.LAZY)
- private PostDetails details;
-
- @ManyToMany
- @JoinTable(name = "post_tag",
- joinColumns = @JoinColumn(name = "post_id"),
- inverseJoinColumns = @JoinColumn(name = "tag_id")
- )
- private List tags = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public PostDetails getDetails() {
- return details;
- }
-
- public List getTags() {
- return tags;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
-
- public void addDetails(PostDetails details) {
- this.details = details;
- details.setPost(this);
- }
-
- public void removeDetails() {
- this.details.setPost(null);
- this.details = null;
- }
- }
-
- @Entity(name = "PostDetails")
- @Table(name = "post_details")
- public static class PostDetails {
-
- @Id
- private Long id;
-
- @Column(name = "created_on")
- private Date createdOn;
-
- @Column(name = "created_by")
- private String createdBy;
-
- public PostDetails() {
- createdOn = new Date();
- }
-
- @OneToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "id")
- @MapsId
- private Post post;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public Date getCreatedOn() {
- return createdOn;
- }
-
- public void setCreatedOn(Date createdOn) {
- this.createdOn = createdOn;
- }
-
- public String getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne
- private Post post;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-
- @Entity(name = "Tag")
- @Table(name = "tag")
- public static class Tag {
-
- @Id
- private Long id;
-
- private String name;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/ManyToOneTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/ManyToOneTest.java
deleted file mode 100644
index 6d2806ade..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/ManyToOneTest.java
+++ /dev/null
@@ -1,154 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import java.util.List;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-
-/**
- * @author Vlad Mihalcea
- */
-public class ManyToOneTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post = new Post("First post");
- entityManager.persist(post);
- });
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- PostComment comment = new PostComment("My review");
- comment.setPost(post);
- entityManager.persist(comment);
-
- entityManager.flush();
- comment.setPost(null);
- });
- }
-
- @Test
- public void testThreePostComments() {
- doInJPA(entityManager -> {
- Post post = new Post("First post");
- entityManager.persist(post);
- });
- doInJPA(entityManager -> {
- Post post = entityManager.getReference(Post.class, 1L);
-
- PostComment comment1 = new PostComment( "My first review");
- comment1.setPost( post );
- PostComment comment2 = new PostComment( "My second review");
- comment2.setPost( post );
- PostComment comment3 = new PostComment( "My third review");
- comment3.setPost( post );
-
- entityManager.persist(comment1);
- entityManager.persist(comment2);
- entityManager.persist(comment3);
- });
-
- doInJPA(entityManager -> {
- PostComment comment1 = entityManager.getReference(PostComment.class, 2L);
-
- entityManager.remove(comment1);
- });
-
- doInJPA(entityManager -> {
- List comments = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "where pc.post.id = :postId", PostComment.class)
- .setParameter( "postId", 1L )
- .getResultList();
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(String title) {
- this.title = title;
- }
-
- 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;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String review;
-
- @ManyToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "post_id")
- private Post post;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalManyToManyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalManyToManyTest.java
deleted file mode 100644
index af6088c70..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalManyToManyTest.java
+++ /dev/null
@@ -1,154 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Vlad Mihalcea
- */
-public class UnidirectionalManyToManyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- Tag.class
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- post1.getTags().add(tag1);
- post1.getTags().add(tag2);
-
- post2.getTags().add(tag1);
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- entityManager.flush();
-
- LOGGER.info("Remove");
-
- post1.getTags().remove(tag1);
- });
- }
-
- @Test
- public void testRemove() {
- final Long postId = doInJPA(entityManager -> {
- Post post1 = new Post("JPA with Hibernate");
- Post post2 = new Post("Native Hibernate");
-
- Tag tag1 = new Tag("Java");
- Tag tag2 = new Tag("Hibernate");
-
- post1.getTags().add(tag1);
- post1.getTags().add(tag2);
-
- post2.getTags().add(tag1);
-
- entityManager.persist(post1);
- entityManager.persist(post2);
-
- return post1.id;
- });
- doInJPA(entityManager -> {
- LOGGER.info("Remove");
- Post post1 = entityManager.find(Post.class, postId);
- entityManager.remove(post1);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE})
- @JoinTable(name = "post_tag",
- joinColumns = @JoinColumn(name = "post_id"),
- inverseJoinColumns = @JoinColumn(name = "tag_id")
- )
- private List tags = new ArrayList<>();
-
- 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 List getTags() {
- return tags;
- }
- }
-
- @Entity(name = "Tag")
- @Table(name = "tag")
- public static class Tag {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String name;
-
- public Tag() {}
-
- public Tag(String name) {
- this.name = name;
- }
-
- 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;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOneToManyJoinColumnTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOneToManyJoinColumnTest.java
deleted file mode 100644
index eb3147b12..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOneToManyJoinColumnTest.java
+++ /dev/null
@@ -1,131 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Vlad Mihalcea
- */
-public class UnidirectionalOneToManyJoinColumnTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void testRemoveTail() {
- doInJPA(entityManager -> {
- Post post = new Post("First post");
-
- post.getComments().add(new PostComment("My first review"));
- post.getComments().add(new PostComment("My second review"));
- post.getComments().add(new PostComment("My third review"));
-
- entityManager.persist(post);
- entityManager.flush();
-
- LOGGER.info("Remove tail");
- post.getComments().remove(2);
- });
- }
-
- @Test
- public void testRemoveHead() {
- doInJPA(entityManager -> {
- Post post = new Post("First post");
-
- post.getComments().add(new PostComment("My first review"));
- post.getComments().add(new PostComment("My second review"));
- post.getComments().add(new PostComment("My third review"));
-
- entityManager.persist(post);
- entityManager.flush();
-
- entityManager.flush();
- LOGGER.info("Remove head");
- post.getComments().remove(0);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
- @JoinColumn(name = "post_id")
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOneToManySetTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOneToManySetTest.java
deleted file mode 100644
index 6bec0613d..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOneToManySetTest.java
+++ /dev/null
@@ -1,133 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.nio.ByteBuffer;
-import java.util.*;
-
-/**
- * @author Vlad Mihalcea
- */
-public class UnidirectionalOneToManySetTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post = new Post("First post");
-
- post.getComments().add(new PostComment("My first review"));
- post.getComments().add(new PostComment("My second review"));
- post.getComments().add(new PostComment("My third review"));
-
- entityManager.persist(post);
- entityManager.flush();
-
- for(PostComment comment: new ArrayList<>(post.getComments())) {
- post.getComments().remove(comment);
- }
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
- private Set comments = new HashSet<>();
-
- 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 Set getComments() {
- return comments;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String slug;
-
- private String review;
-
- public PostComment() {
- byte[] bytes = new byte[8];
- ByteBuffer.wrap(bytes).putDouble(Math.random());
- slug = Base64.getEncoder().encodeToString(bytes);
- }
-
- public PostComment(String review) {
- this();
- this.review = review;
- }
-
- public String getSlug() {
- return slug;
- }
-
- public void setSlug(String slug) {
- this.slug = slug;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- PostComment comment = (PostComment) o;
- return Objects.equals(slug, comment.slug);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(slug);
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOneToManyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOneToManyTest.java
deleted file mode 100644
index 8407add3f..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOneToManyTest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Vlad Mihalcea
- */
-public class UnidirectionalOneToManyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post = new Post("First post");
-
- post.getComments().add(new PostComment("My first review"));
- post.getComments().add(new PostComment("My second review"));
- post.getComments().add(new PostComment("My third review"));
-
- entityManager.persist(post);
- entityManager.flush();
-
- LOGGER.info("Remove tail");
- post.getComments().remove(2);
- entityManager.flush();
- LOGGER.info("Remove head");
- post.getComments().remove(0);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOrderedOneToManyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOrderedOneToManyTest.java
deleted file mode 100644
index 9a85ba69d..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/UnidirectionalOrderedOneToManyTest.java
+++ /dev/null
@@ -1,116 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.association;
-
-import com.vladmihalcea.book.hpjp.util.AbstractMySQLIntegrationTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Vlad Mihalcea
- */
-public class UnidirectionalOrderedOneToManyTest extends AbstractMySQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void testLifecycle() {
- doInJPA(entityManager -> {
- Post post = new Post("First post");
-
- post.getComments().add(new PostComment("My first review"));
- post.getComments().add(new PostComment("My second review"));
- post.getComments().add(new PostComment("My third review"));
-
- entityManager.persist(post);
- entityManager.flush();
-
- LOGGER.info("Remove tail");
- post.getComments().remove(2);
- entityManager.flush();
- LOGGER.info("Remove head");
- post.getComments().remove(0);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
- @OrderColumn(name = "entry")
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/BatchExceptionTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/BatchExceptionTest.java
deleted file mode 100644
index 56209f458..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/BatchExceptionTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.batch;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.Session;
-import org.hibernate.jdbc.Work;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.sql.*;
-import java.util.*;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Vlad Mihalcea
- */
-public class BatchExceptionTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.jdbc.batch_size", "5");
- properties.put("hibernate.order_inserts", "true");
- properties.put("hibernate.order_updates", "true");
- properties.put("hibernate.jdbc.batch_versioned_data", "true");
- return properties;
- }
-
- @Test
- public void testInsertConstraintViolation() {
- LOGGER.info("testInsertPosts");
- doInJPA(entityManager -> {
- Session session = entityManager.unwrap(Session.class);
- session.doWork(connection -> {
-
- try (PreparedStatement st = connection.prepareStatement(
- "INSERT INTO post (id, title) " +
- "VALUES (?, ?)")) {
- for (long i = 0; i < 5; i++) {
- st.setLong(1, i % 2);
- st.setString(2, String.format("High-Performance Java Persistence, Part %d", i));
- st.addBatch();
- }
- st.executeBatch();
- } catch (BatchUpdateException e) {
- LOGGER.info("Batch has managed to process {} entries", e.getUpdateCounts().length);
- }
- });
-
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- 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;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/BatchTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/BatchTest.java
deleted file mode 100644
index ad5938f74..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/BatchTest.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.batch;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.Session;
-import org.jboss.logging.Logger;
-import org.junit.Test;
-
-import javax.persistence.*;
-
-/**
- * @author Vlad Mihalcea
- */
-public class BatchTest extends AbstractTest {
-
- private static final Logger log = Logger.getLogger( BatchTest.class );
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class
- };
- }
-
- @Test
- public void testScroll() {
- withBatchAndSessionManagement();
- }
-
- private void withBatch() {
- int entityCount = 20;
- EntityManager entityManager = null;
- EntityTransaction txn = null;
- try {
- entityManager = entityManagerFactory().createEntityManager();
- entityManager.unwrap(Session.class).setJdbcBatchSize(10);
-
- txn = entityManager.getTransaction();
- txn.begin();
-
- int entityManagerBatchSize = 20;
-
- for ( long i = 0; i < entityCount; ++i ) {
- Post person = new Post( i, String.format( "Post nr %d", i ));
- entityManager.persist( person );
-
- if ( i > 0 && i % entityManagerBatchSize == 0 ) {
- entityManager.flush();
- entityManager.clear();
- }
- }
-
- txn.commit();
- } catch (RuntimeException e) {
- if ( txn != null && txn.isActive()) {
- txn.rollback();
- }
- throw e;
- } finally {
- if (entityManager != null) {
- entityManager.close();
- }
- }
- }
-
- private void withBatchAndSessionManagement() {
- int entityCount = 20;
-
- doInJPA(entityManager -> {
- entityManager.unwrap(Session.class).setJdbcBatchSize(10);
-
- for ( long i = 0; i < entityCount; ++i ) {
- Post person = new Post( i, String.format( "Post nr %d", i ));
- entityManager.persist( person );
- }
- });
- }
-
- private void withBatchAndResetBackToGlobalSetting() {
- EntityManager entityManager = null;
- try {
- entityManager = entityManagerFactory().createEntityManager();
- entityManager.getTransaction().begin();
-
-
- } finally {
- if (entityManager != null) {
- entityManager.getTransaction().rollback();
- entityManager.close();
- }
- }
- }
-
- @Entity(name = "Post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String name;
-
- public Post() {}
-
- public Post(long id, String name) {
- this.id = id;
- this.name = name;
- }
-
- public Long getId() {
- return id;
- }
-
- public String getName() {
- return name;
- }
- }
-
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/BatchingTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/BatchingTest.java
deleted file mode 100644
index e8e9797ab..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/BatchingTest.java
+++ /dev/null
@@ -1,251 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.batch;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * BatchingTest - Test to check the JDBC batch support
- *
- * @author Vlad Mihalcea
- */
-public class BatchingTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.jdbc.batch_size", "5");
- properties.put("hibernate.order_inserts", "true");
- properties.put("hibernate.order_updates", "true");
- properties.put("hibernate.jdbc.batch_versioned_data", "true");
- return properties;
- }
-
- @Test
- public void testInsertPosts() {
- LOGGER.info("testInsertPosts");
- insertPosts();
- }
-
- @Test
- public void testInsertPostsAndComments() {
- LOGGER.info("testInsertPostsAndComments");
- insertPostsAndComments();
- }
-
- @Test
- public void testUpdatePosts() {
- insertPosts();
-
- LOGGER.info("testUpdatePosts");
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p ", Post.class)
- .getResultList();
-
- posts.forEach(post -> post.setTitle(post.getTitle().replaceAll("no", "nr")));
- });
- }
-
- @Test
- public void testUpdatePostsAndComments() {
- insertPostsAndComments();
-
- LOGGER.info("testUpdatePostsAndComments");
- doInJPA(entityManager -> {
- List comments = entityManager.createQuery(
- "select c " +
- "from PostComment c " +
- "join fetch c.post ", PostComment.class)
- .getResultList();
-
- comments.forEach(comment -> {
- comment.setReview(comment.getReview().replaceAll("Good", "Very good"));
- Post post = comment.getPost();
- post.setTitle(post.getTitle().replaceAll("no", "nr"));
- });
- });
- }
-
- @Test
- public void testDeletePosts() {
- insertPosts();
-
- LOGGER.info("testDeletePosts");
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p ", Post.class)
- .getResultList();
-
- posts.forEach(entityManager::remove);
- });
- }
-
- @Test
- public void testDeletePostsAndComments() {
- insertPostsAndComments();
-
- LOGGER.info("testDeletePostsAndComments");
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.comments ", Post.class)
- .getResultList();
-
- posts.forEach(entityManager::remove);
- });
- }
-
- @Test
- public void testDeletePostsAndCommentsWithManualChildRemoval() {
- insertPostsAndComments();
-
- LOGGER.info("testDeletePostsAndCommentsWithManualChildRemoval");
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.comments ", Post.class)
- .getResultList();
-
- for (Post post : posts) {
- for (Iterator commentIterator = post.getComments().iterator();
- commentIterator.hasNext(); ) {
- PostComment comment = commentIterator.next();
- comment.setPost(null);
- commentIterator.remove();
- }
- }
- entityManager.flush();
- posts.forEach(entityManager::remove);
- });
- }
-
- private void insertPosts() {
- doInJPA(entityManager -> {
- for (int i = 0; i < 3; i++) {
- entityManager.persist(new Post(String.format("Post no. %d", i + 1)));
- }
- });
- }
-
- private void insertPostsAndComments() {
- doInJPA(entityManager -> {
- for (int i = 0; i < 3; i++) {
- Post post = new Post(String.format("Post no. %d", i));
- post.addComment(new PostComment("Good"));
- entityManager.persist(post);
- }
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
- private Long id;
-
- @ManyToOne
- private Post post;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/DeletingWithSQLCascadeBatchingTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/DeletingWithSQLCascadeBatchingTest.java
deleted file mode 100644
index c7fa5dfe1..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/DeletingWithSQLCascadeBatchingTest.java
+++ /dev/null
@@ -1,212 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.batch;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.annotations.OnDelete;
-import org.hibernate.annotations.OnDeleteAction;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * DeletingWithoutCascadeBatchingTest - Test to check the JDBC batch support for delete
- *
- * @author Vlad Mihalcea
- */
-public class DeletingWithSQLCascadeBatchingTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.jdbc.batch_size", "5");
- properties.put("hibernate.order_inserts", "true");
- properties.put("hibernate.order_updates", "true");
- properties.put("hibernate.jdbc.batch_versioned_data", "true");
- return properties;
- }
-
- @Test
- public void testDeletePostsAndCommentsWithSQLCascade() {
- insertPostsAndComments();
-
- LOGGER.info("testDeletePostsAndCommentsWithSQLCascade");
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p ", Post.class)
- .getResultList();
-
- posts.forEach(entityManager::remove);
- });
- }
-
- @Test
- public void testDeletePostsAndCommentsWithSQLCascadeAndManagedChildren() {
- insertPostsAndComments();
-
- LOGGER.info("testDeletePostsAndCommentsWithSQLCascadeAndManagedChildren");
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p ", Post.class)
- .getResultList();
-
- List comments = entityManager.createQuery(
- "select c " +
- "from PostComment c " +
- "where c.post in :posts", PostComment.class)
- .setParameter("posts", posts)
- .getResultList();
-
- posts.forEach(entityManager::remove);
-
- comments.forEach(comment -> comment.setReview("Excellent"));
- });
- }
-
- @Test
- public void testDeletePostsAndCommentsWithSQLCascadeAndManagedChildrenFloating() {
- insertPostsAndComments();
-
- LOGGER.info("testDeletePostsAndCommentsWithSQLCascadeAndManagedChildrenFloating");
- try {
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p ", Post.class)
- .getResultList();
-
- List comments = entityManager.createQuery(
- "select c " +
- "from PostComment c " +
- "where c.post in :posts", PostComment.class)
- .setParameter("posts", posts)
- .getResultList();
-
- posts.forEach(entityManager::remove);
- entityManager.flush();
-
- comments.forEach(comment -> comment.setReview("Excellent"));
- });
- } catch (PersistenceException e) {
- assertEquals(OptimisticLockException.class, e.getCause().getClass());
- }
- }
-
- private void insertPostsAndComments() {
- doInJPA(entityManager -> {
- for (int i = 0; i < 3; i++) {
- Post post = new Post(String.format("Post no. %d", i));
- post.addComment(new PostComment("Good"));
- entityManager.persist(post);
- }
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "post")
- @OnDelete(action = OnDeleteAction.CASCADE)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
- private Long id;
-
- @ManyToOne
- @org.hibernate.annotations.ForeignKey(name = "fk_post_comment_post")
- private Post post;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/DeletingWithoutCascadeBatchingTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/DeletingWithoutCascadeBatchingTest.java
deleted file mode 100644
index 41ec58e1d..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/batch/DeletingWithoutCascadeBatchingTest.java
+++ /dev/null
@@ -1,161 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.batch;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * DeletingWithoutCascadeBatchingTest - Test to check the JDBC batch support for delete
- *
- * @author Vlad Mihalcea
- */
-public class DeletingWithoutCascadeBatchingTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.jdbc.batch_size", "5");
- properties.put("hibernate.order_inserts", "true");
- properties.put("hibernate.order_updates", "true");
- properties.put("hibernate.jdbc.batch_versioned_data", "true");
- return properties;
- }
-
- @Test
- public void testDeletePostsAndCommentsWithBulkDelete() {
- insertPostsAndComments();
-
- LOGGER.info("testDeletePostsAndCommentsWithBulkDelete");
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "where p.title like 'Post no%'", Post.class)
- .getResultList();
-
- entityManager.createQuery(
- "delete " +
- "from PostComment c " +
- "where c.post in :posts")
- .setParameter("posts", posts)
- .executeUpdate();
-
- posts.forEach(entityManager::remove);
- });
- }
-
- private void insertPostsAndComments() {
- doInJPA(entityManager -> {
- for (int i = 0; i < 3; i++) {
- Post post = new Post(String.format("Post no. %d", i));
- post.addComment(new PostComment("Good"));
- entityManager.persist(post);
- }
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "post")
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
- private Long id;
-
- @ManyToOne
- private Post post;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/binding/EntityGraphMapperTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/binding/EntityGraphMapperTest.java
deleted file mode 100644
index f746fd550..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/binding/EntityGraphMapperTest.java
+++ /dev/null
@@ -1,166 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.binding;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import com.vladmihalcea.book.hpjp.util.exception.DataAccessException;
-import com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider;
-import org.junit.Test;
-
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import static com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider.Post;
-import static com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider.PostComment;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-/**
- * EntityGraphMapperTest - Test mapping to entity
- *
- * @author Vlad Mihalcea
- */
-public class EntityGraphMapperTest extends AbstractTest {
-
- public static final String INSERT_POST = "insert into post (title, version, id) values (?, ?, ?)";
-
- public static final String INSERT_POST_COMMENT = "insert into post_comment (post_id, review, version, id) values (?, ?, ?, ?)";
-
- public static final String INSERT_POST_DETAILS= "insert into post_details (id, created_on, version) values (?, ?, ?)";
-
- private BlogEntityProvider entityProvider = new BlogEntityProvider();
-
- private Long id = 1L;
- private long expectedCount = 2;
-
- @Override
- protected Class>[] entities() {
- return entityProvider.entities();
- }
-
- @Override
- public void init() {
- super.init();
- doInJDBC(connection -> {
- try (
- PreparedStatement postStatement = connection.prepareStatement(INSERT_POST);
- PreparedStatement postCommentStatement = connection.prepareStatement(INSERT_POST_COMMENT);
- PreparedStatement postDetailsStatement = connection.prepareStatement(INSERT_POST_DETAILS);
- ) {
-
- int postCount = getPostCount();
- int postCommentCount = getPostCommentCount();
-
- int index;
-
- for (int i = 0; i < postCount; i++) {
- if (i > 0 && i % 100 == 0) {
- postStatement.executeBatch();
- postDetailsStatement.executeBatch();
- }
-
- index = 0;
- postStatement.setString(++index, String.format("Post no. %1$d", i));
- postStatement.setInt(++index, i);
- postStatement.setLong(++index, i);
- postStatement.addBatch();
-
- index = 0;
- postDetailsStatement.setInt(++index, i);
- postDetailsStatement.setTimestamp(++index, new Timestamp(System.currentTimeMillis()));
- postDetailsStatement.setInt(++index, i);
- postDetailsStatement.addBatch();
- }
- postStatement.executeBatch();
- postDetailsStatement.executeBatch();
-
- for (int i = 0; i < postCount; i++) {
- for (int j = 0; j < postCommentCount; j++) {
- index = 0;
- postCommentStatement.setLong(++index, i);
- postCommentStatement.setString(++index, String.format("Post comment %1$d", j));
- postCommentStatement.setInt(++index, i);
- postCommentStatement.setLong(++index, (postCommentCount * i) + j);
- postCommentStatement.addBatch();
- if (j % 100 == 0) {
- postCommentStatement.executeBatch();
- }
- }
- }
- postCommentStatement.executeBatch();
- } catch (SQLException e) {
- fail(e.getMessage());
- }
- });
- }
-
- @Test
- public void testJdbcOneToManyMapping() {
- doInJDBC(connection -> {
- try (PreparedStatement statement = connection.prepareStatement(
- "SELECT * " +
- "FROM post AS p " +
- "JOIN post_comment AS pc ON p.id = pc.post_id " +
- "WHERE " +
- " p.id BETWEEN ? AND ? + 1"
- )) {
- statement.setLong(1, id);
- statement.setLong(2, id);
- try (ResultSet resultSet = statement.executeQuery()) {
- List posts = toPosts(resultSet);
- assertEquals(expectedCount, posts.size());
- }
- } catch (SQLException e) {
- throw new DataAccessException( e);
- }
- });
- }
-
- private List toPosts(ResultSet resultSet) throws SQLException {
- Map postMap = new LinkedHashMap<>();
- while (resultSet.next()) {
- Long postId = resultSet.getLong(1);
- Post post = postMap.get(postId);
- if(post == null) {
- post = new Post(postId);
- postMap.put(postId, post);
- post.setTitle(resultSet.getString(2));
- post.setVersion(resultSet.getInt(3));
- }
- PostComment comment = new PostComment();
- comment.setId(resultSet.getLong(4));
- comment.setReview(resultSet.getString(5));
- comment.setVersion(resultSet.getInt(6));
- post.addComment(comment);
- }
- return new ArrayList<>(postMap.values());
- }
-
- @Test
- public void testJPAParameterBinding() {
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select distinct p " +
- "from Post p " +
- "join fetch p.comments " +
- "where " +
- " p.id BETWEEN :id AND :id + 1",
- Post.class)
- .setParameter("id", id)
- .getResultList();
- assertEquals(expectedCount, posts.size());
- });
- }
-
- protected int getPostCount() {
- return 10;
- }
-
- protected int getPostCommentCount() {
- return 10;
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/bytecode/BytecodeEnhancedOneToOneTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/bytecode/BytecodeEnhancedOneToOneTest.java
deleted file mode 100644
index c33d62073..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/bytecode/BytecodeEnhancedOneToOneTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.bytecode;
-
-import com.vladmihalcea.book.hpjp.hibernate.forum.Post;
-import com.vladmihalcea.book.hpjp.hibernate.forum.PostComment;
-import com.vladmihalcea.book.hpjp.hibernate.forum.PostDetails;
-import com.vladmihalcea.book.hpjp.hibernate.forum.Tag;
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-/**
- * @author Vlad Mihalcea
- */
-public class BytecodeEnhancedOneToOneTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostDetails.class,
- PostComment.class,
- Tag.class
- };
- }
-
- @Test
- public void testDirtyChecking() {
- doInJPA(entityManager -> {
- Post post = new Post("First post");
- post.setId(1L);
- PostDetails details = new PostDetails();
- post.addDetails(details);
- entityManager.persist(post);
- });
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- });
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/bytecode/BytecodeEnhancedTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/bytecode/BytecodeEnhancedTest.java
deleted file mode 100644
index 7fc67de1a..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/bytecode/BytecodeEnhancedTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.bytecode;
-
-import com.vladmihalcea.book.hpjp.hibernate.forum.Post;
-import com.vladmihalcea.book.hpjp.hibernate.forum.PostComment;
-import com.vladmihalcea.book.hpjp.hibernate.forum.PostDetails;
-import com.vladmihalcea.book.hpjp.hibernate.forum.Tag;
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Test;
-
-/**
- * BytecodeEnhancedTest - Test to check dirty checking capabilities
- *
- * @author Vlad Mihalcea
- */
-public class BytecodeEnhancedTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostDetails.class,
- PostComment.class,
- Tag.class
- };
- }
-
- @Test
- public void testDirtyChecking() {
- doInJPA(entityManager -> {
- Post post = new Post(1L);
- post.setTitle("Postit");
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("Good");
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Excellent");
-
- post.addComment(comment1);
- post.addComment(comment2);
- entityManager.persist(post);
- });
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
-
- post.setTitle("Post it");
- entityManager.flush();
- });
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/CollectionHydratedStateTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/CollectionHydratedStateTest.java
deleted file mode 100644
index 75c1bbdb5..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/CollectionHydratedStateTest.java
+++ /dev/null
@@ -1,154 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.annotations.Cache;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Vlad Mihalcea
- */
-public class CollectionHydratedStateTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- properties.put("hibernate.generate_statistics", Boolean.TRUE.toString());
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("JDBC part review");
- post.addComment(comment1);
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Hibernate part review");
- post.addComment(comment2);
-
- entityManager.persist(post);
- });
- }
-
- @Test
- public void testEntityLoad() {
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("Load from cache");
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- }
-
- @Entity(name = "Post")
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true)
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne
- private Post post;
-
- private String review;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/EntityHydratedStateTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/EntityHydratedStateTest.java
deleted file mode 100644
index 917d8ef27..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/EntityHydratedStateTest.java
+++ /dev/null
@@ -1,210 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.annotations.Cache;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.Date;
-import java.util.Properties;
-
-import static org.junit.Assert.assertNotNull;
-
-/**
- * @author Vlad Mihalcea
- */
-public class EntityHydratedStateTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostDetails.class,
- PostComment.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- properties.put("hibernate.generate_statistics", Boolean.TRUE.toString());
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
- entityManager.persist(post);
-
- PostDetails details = new PostDetails();
- details.setCreatedBy("Vlad Mihalcea");
- details.setCreatedOn(new Date());
- details.setPost(post);
- entityManager.persist(details);
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("JDBC part review");
- comment1.setPost(post);
- entityManager.persist(comment1);
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Hibernate part review");
- comment2.setPost(post);
- entityManager.persist(comment2);
- });
- }
-
- @Test
- public void testEntityLoad() {
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertNotNull(post);
- PostDetails details = entityManager.find(PostDetails.class, 1L);
- assertNotNull(details);
- PostComment comment = entityManager.find(PostComment.class, 1L);
- assertNotNull(comment);
- });
-
- printCacheRegionStatistics(Post.class.getName());
-
- doInJPA(entityManager -> {
- LOGGER.info("Load from cache");
- Post post = entityManager.find(Post.class, 1L);
- assertNotNull(post);
- PostDetails details = entityManager.find(PostDetails.class, 1L);
- assertNotNull(details);
- PostComment comment = entityManager.find(PostComment.class, 1L);
- assertNotNull(comment);
- });
-
- printCacheRegionStatistics(Post.class.getName());
-
- }
-
- @Entity(name = "Post")
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- 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;
- }
- }
-
- @Entity(name = "PostDetails")
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class PostDetails {
-
- @Id
- private Long id;
-
- @Column(name = "created_on")
- private Date createdOn;
-
- @Column(name = "created_by")
- private String createdBy;
-
- @OneToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "id")
- @MapsId
- private Post post;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public Date getCreatedOn() {
- return createdOn;
- }
-
- public void setCreatedOn(Date createdOn) {
- this.createdOn = createdOn;
- }
-
- public String getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
- }
-
- @Entity(name = "PostComment")
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne
- private Post post;
-
- private String review;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/HydratedStateBenchmarkTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/HydratedStateBenchmarkTest.java
deleted file mode 100644
index a0a52158a..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/HydratedStateBenchmarkTest.java
+++ /dev/null
@@ -1,196 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache;
-
-import com.codahale.metrics.MetricRegistry;
-import com.codahale.metrics.Slf4jReporter;
-import com.codahale.metrics.Timer;
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.hibernate.annotations.Immutable;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
-import javax.persistence.*;
-import java.io.Serializable;
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-
-import static org.junit.Assert.assertNotNull;
-
-
-/**
- * @author Vlad Mihalcea
- */
-@RunWith(Parameterized.class)
-public class HydratedStateBenchmarkTest extends AbstractTest {
-
- private MetricRegistry metricRegistry = new MetricRegistry();
-
- private Timer timer = metricRegistry.timer(getClass().getSimpleName());
-
- private Slf4jReporter logReporter = Slf4jReporter
- .forRegistry(metricRegistry)
- .outputTo(LOGGER)
- .build();
-
- private int insertCount;
-
- public HydratedStateBenchmarkTest(int insertCount) {
- this.insertCount = insertCount;
- }
-
- @Parameterized.Parameters
- public static Collection dataProvider() {
- List providers = new ArrayList<>();
- providers.add(new Object[]{100});
- providers.add(new Object[]{500});
- providers.add(new Object[]{1000});
- providers.add(new Object[]{5000});
- providers.add(new Object[]{10000});
- return providers;
- }
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostDetails.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.use_second_level_cache", Boolean.TRUE.toString());
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
-
- properties.put("hibernate.jdbc.batch_size", "100");
- properties.put("hibernate.order_inserts", "true");
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- for (long i = 0; i < insertCount; i++) {
- Post post = new Post();
- post.setId(i);
- post.setTitle("High-Performance Java Persistence");
- entityManager.persist(post);
-/*
- PostDetails details = new PostDetails();
- details.setCreatedBy("Vlad Mihalcea");
- details.setCreatedOn(new Date());
- details.setPost(post);
- entityManager.persist(details);*/
- }
- });
- }
-
- @Test
- public void testReadOnlyFetchPerformance() {
- //warming-up
- doInJPA(entityManager -> {
- for (long i = 0; i < 10000; i++) {
- Post post = entityManager.find(Post.class, i % insertCount);
- //PostDetails details = entityManager.find(PostDetails.class, i);
- assertNotNull(post);
- }
- });
- doInJPA(entityManager -> {
- long startNanos = System.nanoTime();
- for (long i = 0; i < insertCount; i++) {
- Post post = entityManager.find(Post.class, i);
- //PostDetails details = entityManager.find(PostDetails.class, i);
- }
- timer.update(System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
- });
- logReporter.report();
- }
-
-
- @Entity(name = "Post")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- @org.hibernate.annotations.Immutable
- public static class Post implements Serializable {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- 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;
- }
- }
-
- @Entity(name = "PostDetails")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- @Immutable
- //This does not work since it features an association type
- public static class PostDetails implements Serializable {
-
- @Id
- private Long id;
-
- @Column(name = "created_on")
- private Date createdOn;
-
- @Column(name = "created_by")
- private String createdBy;
-
- @OneToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "id")
- @MapsId
- private Post post;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public Date getCreatedOn() {
- return createdOn;
- }
-
- public void setCreatedOn(Date createdOn) {
- this.createdOn = createdOn;
- }
-
- public String getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/HydratedStateReferenceEntitiesTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/HydratedStateReferenceEntitiesTest.java
deleted file mode 100644
index c9604267a..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/HydratedStateReferenceEntitiesTest.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache;
-
-import java.util.Properties;
-
-
-/**
- * ReadOnlyCacheConcurrencyStrategyReferenceEntitiesTest - Test to check CacheConcurrencyStrategy.READ_ONLY
- * with hibernate.cache.use_reference_entries doesn't work because Commit has a collection of CommitChanges
- *
- * @author Vlad Mihalcea
- */
-public class HydratedStateReferenceEntitiesTest extends HydratedStateBenchmarkTest {
-
- public HydratedStateReferenceEntitiesTest(int insertCount) {
- super(insertCount);
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.use_reference_entries", Boolean.TRUE.toString());
- return properties;
- }
-
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/QueryCacheTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/QueryCacheTest.java
deleted file mode 100644
index 15b1522de..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/QueryCacheTest.java
+++ /dev/null
@@ -1,350 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.SQLQuery;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.hibernate.cache.internal.StandardQueryCache;
-import org.hibernate.jpa.QueryHints;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-/**
- * QueryCacheTest - Test to check the 2nd level query cache
- *
- * @author Vlad Mihalcea
- */
-public class QueryCacheTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.use_second_level_cache", Boolean.TRUE.toString());
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- properties.put("hibernate.cache.use_query_cache", Boolean.TRUE.toString());
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
-
- PostComment comment = new PostComment();
- comment.setId(1L);
- comment.setReview("JDBC part review");
- post.addComment(comment);
-
- entityManager.persist(post);
- });
- }
-
- @After
- public void destroy() {
- entityManagerFactory().getCache().evictAll();
- super.destroy();
- }
-
- public List getLatestPostComments(EntityManager entityManager) {
- return entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "order by pc.post.id desc", PostComment.class)
- .setMaxResults(10)
- .setHint(QueryHints.HINT_CACHEABLE, true)
- .getResultList();
- }
-
- private List getLatestPostCommentsByPostId(EntityManager entityManager) {
- return entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "where pc.post.id = :postId", PostComment.class)
- .setParameter("postId", 1L)
- .setMaxResults(10)
- .setHint(QueryHints.HINT_CACHEABLE, true)
- .getResultList();
- }
-
- private List getLatestPostCommentsByPost(EntityManager entityManager) {
- Post post = entityManager.find(Post.class, 1L);
- return entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "where pc.post = :post ", PostComment.class)
- .setParameter("post", post)
- .setMaxResults(10)
- .setHint(QueryHints.HINT_CACHEABLE, true)
- .getResultList();
- }
-
- private List getPostCommentSummaryByPost(EntityManager entityManager) {
- return entityManager.createQuery(
- "select new com.vladmihalcea.book.hpjp.hibernate.cache.QueryCacheTest$PostCommentSummary(pc.id, p.title, pc.review) " +
- "from PostComment pc " +
- "left join pc.post p " +
- "where p.id = :postId ", PostCommentSummary.class)
- .setParameter("postId", 1L)
- .setMaxResults(10)
- .setHint(QueryHints.HINT_CACHEABLE, true)
- .getResultList();
- }
-
- @Test
- public void test2ndLevelCacheWithoutResults() {
- doInJPA(entityManager -> {
- entityManager.createQuery("delete from PostComment").executeUpdate();
- });
- doInJPA(entityManager -> {
- LOGGER.info("Query cache with basic type parameter");
- List comments = getLatestPostCommentsByPostId(entityManager);
- assertTrue(comments.isEmpty());
- });
- doInJPA(entityManager -> {
- LOGGER.info("Query cache with entity type parameter");
- List comments = getLatestPostCommentsByPostId(entityManager);
- assertTrue(comments.isEmpty());
- });
- }
-
- @Test
- public void test2ndLevelCacheWithQuery() {
- doInJPA(entityManager -> {
- printCacheRegionStatistics(StandardQueryCache.class.getName());
- assertEquals(1, getLatestPostComments(entityManager).size());
- printCacheRegionStatistics(StandardQueryCache.class.getName());
- });
- }
-
- @Test
- public void test2ndLevelCacheWithParameters() {
- doInJPA(entityManager -> {
- LOGGER.info("Query cache with basic type parameter");
- List comments = getLatestPostCommentsByPostId(entityManager);
- assertEquals(1, comments.size());
- });
- doInJPA(entityManager -> {
- LOGGER.info("Query cache with entity type parameter");
- List comments = getLatestPostCommentsByPost(entityManager);
- assertEquals(1, comments.size());
- });
- }
-
- @Test
- public void test2ndLevelCacheWithProjection() {
- doInJPA(entityManager -> {
- LOGGER.info("Query cache with projection");
- List comments = getPostCommentSummaryByPost(entityManager);
- assertEquals(1, comments.size());
- });
- doInJPA(entityManager -> {
- LOGGER.info("Query cache with projection");
- List comments = getPostCommentSummaryByPost(entityManager);
- assertEquals(1, comments.size());
- });
- }
-
- @Test
- public void test2ndLevelCacheWithQueryInvalidation() {
- doInJPA(entityManager -> {
-
- assertEquals(1, getLatestPostComments(entityManager).size());
- printCacheRegionStatistics(StandardQueryCache.class.getName());
-
- LOGGER.info("Insert a new PostComment");
- PostComment newComment = new PostComment();
- newComment.setId(2L);
- newComment.setReview("JDBC part review");
- Post post = entityManager.find(Post.class, 1L);
- post.addComment(newComment);
- entityManager.flush();
-
- assertEquals(2, getLatestPostComments(entityManager).size());
- printCacheRegionStatistics(StandardQueryCache.class.getName());
- });
-
- LOGGER.info("After transaction commit");
- printCacheRegionStatistics(StandardQueryCache.class.getName());
-
- doInJPA(entityManager -> {
- LOGGER.info("Check query cache");
- assertEquals(2, getLatestPostComments(entityManager).size());
- });
- printCacheRegionStatistics(StandardQueryCache.class.getName());
- }
-
- @Test
- public void test2ndLevelCacheWithNativeQueryInvalidation() {
- doInJPA(entityManager -> {
- assertEquals(1, getLatestPostComments(entityManager).size());
- printCacheRegionStatistics(StandardQueryCache.class.getName());
-
- int postCount = ((Number) entityManager.createNativeQuery(
- "SELECT count(*) FROM post")
- .getSingleResult()).intValue();
-
- assertEquals(postCount, getLatestPostComments(entityManager).size());
- printCacheRegionStatistics(StandardQueryCache.class.getName());
- });
- }
-
- @Test
- public void test2ndLevelCacheWithNativeUpdateStatementInvalidation() {
- doInJPA(entityManager -> {
- assertEquals(1, getLatestPostComments(entityManager).size());
- printCacheRegionStatistics(StandardQueryCache.class.getName());
-
- entityManager.createNativeQuery(
- "UPDATE post SET title = '\"'||title||'\"' ")
- .executeUpdate();
-
- assertEquals(1, getLatestPostComments(entityManager).size());
- printCacheRegionStatistics(StandardQueryCache.class.getName());
- });
- }
-
- @Test
- public void test2ndLevelCacheWithNativeUpdateStatementSynchronization() {
- doInJPA(entityManager -> {
- assertEquals(1, getLatestPostComments(entityManager).size());
- printCacheRegionStatistics(StandardQueryCache.class.getName());
-
- LOGGER.info("Execute native query with synchronization");
- entityManager.createNativeQuery(
- "UPDATE post SET title = '\"'||title||'\"' ")
- .unwrap(SQLQuery.class)
- .addSynchronizedEntityClass(Post.class)
- .executeUpdate();
-
- assertEquals(1, getLatestPostComments(entityManager).size());
- printCacheRegionStatistics(StandardQueryCache.class.getName());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true)
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-
- public static class PostCommentSummary {
-
- private Long commentId;
-
- private String title;
-
- private String review;
-
- public PostCommentSummary(Long commentId, String title, String review) {
- this.commentId = commentId;
- this.title = title;
- this.review = review;
- }
-
- public Long getCommentId() {
- return commentId;
- }
-
- public String getTitle() {
- return title;
- }
-
- public String getReview() {
- return review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/QueryHydratedStateTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/QueryHydratedStateTest.java
deleted file mode 100644
index 694cde591..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/QueryHydratedStateTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.Session;
-import org.hibernate.annotations.Cache;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Version;
-import java.util.List;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Vlad Mihalcea
- */
-public class QueryHydratedStateTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- properties.put("hibernate.generate_statistics", Boolean.TRUE.toString());
- properties.put("hibernate.cache.use_query_cache", Boolean.TRUE.toString());
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post1 = new Post();
- post1.setId(1L);
- post1.setTitle("High-Performance Java Persistence");
-
- entityManager.persist(post1);
-
- Post post2 = new Post();
- post2.setId(2L);
- post2.setTitle("High-Performance Hibernate");
-
- entityManager.persist(post2);
- });
- }
-
- @Test
- public void testEntityLoad() {
-
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "where p.title like :token", Post.class)
- .setParameter("token", "High-Performance%")
- .setHint("org.hibernate.cacheable", true)
- .getResultList();
- assertEquals(1, posts.size());
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("Load from cache");
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "where p.title like :token", Post.class)
- .setParameter("token", "High-Performance%")
- .setHint("org.hibernate.cacheable", true)
- .getResultList();
- assertEquals(1, posts.size());
- });
-
- doInJPA(entityManager -> {
- Session session = entityManager.unwrap(Session.class);
- List posts = (List) session.createQuery(
- "select p " +
- "from Post p " +
- "where p.title like :token")
- .setParameter("token", "High-Performance%")
- .setCacheable(true)
- .list();
- assertEquals(1, posts.size());
- });
- }
-
- @Entity(name = "Post")
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- 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;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/nonstrictreadwrite/NonStrictReadWriteCacheConcurrencyStrategyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/nonstrictreadwrite/NonStrictReadWriteCacheConcurrencyStrategyTest.java
deleted file mode 100644
index 0b7fa2698..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/nonstrictreadwrite/NonStrictReadWriteCacheConcurrencyStrategyTest.java
+++ /dev/null
@@ -1,234 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache.nonstrictreadwrite;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-
-/**
- * @author Vlad Mihalcea
- */
-public class NonStrictReadWriteCacheConcurrencyStrategyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.use_second_level_cache", Boolean.TRUE.toString());
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("JDBC part review");
- post.addComment(comment1);
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Hibernate part review");
- post.addComment(comment2);
-
- entityManager.persist(post);
- });
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- LOGGER.info("Post entity inserted");
- }
-
- @Test
- public void testPostEntityLoad() {
-
- LOGGER.info("Load Post entity and comments collection");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- printCacheRegionStatistics(post.getClass().getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- });
- }
-
- @Test
- public void testPostEntityEvictModifyLoad() {
-
- LOGGER.info("Evict, modify, load");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.detach(post);
-
- post.setTitle("High-Performance Hibernate");
- entityManager.merge(post);
- entityManager.flush();
-
- entityManager.detach(post);
- post = entityManager.find(Post.class, 1L);
- printCacheRegionStatistics(post.getClass().getName());
- });
- }
-
- @Test
- public void testEntityUpdate() {
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- post.setTitle("High-Performance Hibernate");
- PostComment comment = post.getComments().remove(0);
- comment.setPost(null);
- });
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
- }
-
- @Test
- public void testNonVersionedEntityUpdate() {
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L);
- });
- printCacheRegionStatistics(PostComment.class.getName());
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L);
- comment.setReview("JDBC and Database part review");
- });
- printCacheRegionStatistics(PostComment.class.getName());
- }
-
- @Test
- public void testEntityDelete() {
- LOGGER.info("Cache entries can be deleted");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.remove(post);
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertNull(post);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true)
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readonly/IdentityReadOnlyCacheConcurrencyStrategyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readonly/IdentityReadOnlyCacheConcurrencyStrategyTest.java
deleted file mode 100644
index f41ffbc59..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readonly/IdentityReadOnlyCacheConcurrencyStrategyTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache.readonly;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.Properties;
-
-
-/**
- * CacheConcurrencyStrategyTest - Test to check CacheConcurrencyStrategy.READ_ONLY
- *
- * @author Vlad Mihalcea
- */
-public class IdentityReadOnlyCacheConcurrencyStrategyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.use_second_level_cache", Boolean.TRUE.toString());
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setTitle("High-Performance Java Persistence");
- entityManager.persist(post);
- });
- printCacheRegionStatistics(Post.class.getName());
- LOGGER.info("Post entity inserted");
- }
-
- @Test
- public void testPostEntityLoad() {
-
- LOGGER.info("Entities are not loaded from cache for identity as it's read-through");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- printCacheRegionStatistics(post.getClass().getName());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
- public static class Post {
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- 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;
- }
- }
-}
\ No newline at end of file
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readonly/ReadOnlyCacheConcurrencyStrategyImmutableTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readonly/ReadOnlyCacheConcurrencyStrategyImmutableTest.java
deleted file mode 100644
index bf9eb7c1a..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readonly/ReadOnlyCacheConcurrencyStrategyImmutableTest.java
+++ /dev/null
@@ -1,167 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache.readonly;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.hibernate.annotations.Immutable;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-
-/**
- * @author Vlad Mihalcea
- */
-public class ReadOnlyCacheConcurrencyStrategyImmutableTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.use_second_level_cache", Boolean.TRUE.toString());
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("JDBC part review");
- post.addComment(comment1);
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Hibernate part review");
- post.addComment(comment2);
-
- entityManager.persist(post);
- });
- printCacheRegionStatistics(Post.class.getName());
- LOGGER.info("Post entity inserted");
- }
-
- @Test
- public void testReadOnlyEntityUpdate() {
- LOGGER.info("Read-only cache entries cannot be updated");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- post.setTitle("High-Performance Hibernate");
- });
- }
-
- @Test
- public void testCollectionCacheUpdate() {
-
- LOGGER.info("Read-only collection cache entries cannot be updated");
-
- try {
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- PostComment comment = post.getComments().remove(0);
- comment.setPost(null);
- });
- } catch (Exception e) {
- LOGGER.error("Expected", e);
- }
- }
-
- @Entity(name = "Post")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
- @Immutable
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "post")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
- @Immutable
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
- @Immutable
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readonly/ReadOnlyCacheConcurrencyStrategyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readonly/ReadOnlyCacheConcurrencyStrategyTest.java
deleted file mode 100644
index 8344d1a20..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readonly/ReadOnlyCacheConcurrencyStrategyTest.java
+++ /dev/null
@@ -1,275 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache.readonly;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import static org.junit.Assert.*;
-
-
-/**
- * CacheConcurrencyStrategyTest - Test to check CacheConcurrencyStrategy.READ_ONLY
- *
- * @author Vlad Mihalcea
- */
-public class ReadOnlyCacheConcurrencyStrategyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.use_second_level_cache", Boolean.TRUE.toString());
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
- entityManager.persist(post);
- });
- printCacheRegionStatistics(Post.class.getName());
- LOGGER.info("Post entity inserted");
- }
-
- @Test
- public void testPostEntityLoad() {
-
- LOGGER.info("Entities are loaded from cache");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- printCacheRegionStatistics(post.getClass().getName());
- });
- }
-
- @Test
- public void testCollectionCacheLoad() {
- LOGGER.info("Collections require separate caching");
- doInJPA(entityManager -> {
-
- Post post = entityManager.find(Post.class, 1L);
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("JDBC part review");
- post.addComment(comment1);
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Hibernate part review");
- post.addComment(comment2);
- });
-
- printCacheRegionStatistics(Post.class.getName() + ".comments");
-
- doInJPA(entityManager -> {
- LOGGER.info("Load PostComment from database");
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- LOGGER.info("Load PostComment from cache");
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
- }
-
- @Test
- public void testCollectionCacheUpdate() {
-
- doInJPA(entityManager -> {
-
- Post post = entityManager.find(Post.class, 1L);
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("JDBC part review");
- post.addComment(comment1);
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Hibernate part review");
- post.addComment(comment2);
- });
-
- LOGGER.info("Collection cache entries cannot be updated");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- PostComment comment = post.getComments().remove(0);
- comment.setPost(null);
- });
-
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- try {
- doInJPA(entityManager -> {
- LOGGER.info("Load PostComment from cache");
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(1, post.getComments().size());
- });
- } catch (Exception e) {
- LOGGER.error("Expected", e);
- }
- }
-
- @Test
- public void testEntityUpdate() {
- try {
- LOGGER.info("Cache entries cannot be updated");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- post.setTitle("High-Performance Hibernate");
- });
- } catch (Exception e) {
- LOGGER.error("Expected", e);
- }
- }
-
- @Test
- public void testEntityDelete() {
- LOGGER.info("Cache entries can be deleted");
-
- doInJPA(entityManager -> {
-
- Post post = entityManager.find(Post.class, 1L);
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("JDBC part review");
- post.addComment(comment1);
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Hibernate part review");
- post.addComment(comment2);
- });
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.remove(post);
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertNull(post);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true)
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readwrite/IdentityReadWriteCacheConcurrencyStrategyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readwrite/IdentityReadWriteCacheConcurrencyStrategyTest.java
deleted file mode 100644
index 7ac9e25cf..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readwrite/IdentityReadWriteCacheConcurrencyStrategyTest.java
+++ /dev/null
@@ -1,139 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache.readwrite;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-
-/**
- * @author Vlad Mihalcea
- */
-public class IdentityReadWriteCacheConcurrencyStrategyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.use_second_level_cache", Boolean.TRUE.toString());
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setTitle("High-Performance Java Persistence");
- entityManager.persist(post);
- });
- printCacheRegionStatistics(Post.class.getName());
- LOGGER.info("Post entity inserted");
- }
-
- @Test
- public void testPostEntityLoad() {
-
- LOGGER.info("Load Post entity and comments collection");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- printCacheRegionStatistics(post.getClass().getName());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class Post {
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true)
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class PostComment {
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readwrite/ReadWriteCacheConcurrencyStrategyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readwrite/ReadWriteCacheConcurrencyStrategyTest.java
deleted file mode 100644
index 6250abac7..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readwrite/ReadWriteCacheConcurrencyStrategyTest.java
+++ /dev/null
@@ -1,241 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache.readwrite;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-
-/**
- * @author Vlad Mihalcea
- */
-public class ReadWriteCacheConcurrencyStrategyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.cache.use_second_level_cache", Boolean.TRUE.toString());
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- return properties;
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("JDBC part review");
- post.addComment(comment1);
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Hibernate part review");
- post.addComment(comment2);
-
- entityManager.persist(post);
- });
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- LOGGER.info("Post entity inserted");
- }
-
- @Test
- public void testPostEntityLoad() {
-
- LOGGER.info("Load Post entity and comments collection");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- printCacheRegionStatistics(post.getClass().getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- });
- }
-
- @Test
- public void testPostEntityEvictModifyLoad() {
-
- LOGGER.info("Evict, modify, load");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.detach(post);
-
- post.setTitle("High-Performance Hibernate");
- entityManager.merge(post);
- entityManager.flush();
-
- entityManager.detach(post);
- post = entityManager.find(Post.class, 1L);
- printCacheRegionStatistics(post.getClass().getName());
- });
- }
-
- @Test
- public void testEntityUpdate() {
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- post.setTitle("High-Performance Hibernate");
- PostComment comment = post.getComments().remove(0);
- comment.setPost(null);
-
- entityManager.flush();
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- LOGGER.debug("Commit after flush");
- });
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
- }
-
- @Test
- public void testNonVersionedEntityUpdate() {
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L);
- });
- printCacheRegionStatistics(PostComment.class.getName());
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L);
- comment.setReview("JDBC and Database part review");
- });
- printCacheRegionStatistics(PostComment.class.getName());
- }
-
- @Test
- public void testEntityDelete() {
- LOGGER.info("Cache entries can be deleted");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.remove(post);
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertNull(post);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true)
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/TransactionalCacheConcurrencyStrategyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/TransactionalCacheConcurrencyStrategyTest.java
deleted file mode 100644
index 55758760b..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/TransactionalCacheConcurrencyStrategyTest.java
+++ /dev/null
@@ -1,228 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache.transactional;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.vladmihalcea.book.hpjp.util.transaction.JPATransactionVoidFunction;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.transaction.support.TransactionCallback;
-import org.springframework.transaction.support.TransactionTemplate;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.PersistenceContext;
-
-import static com.vladmihalcea.book.hpjp.hibernate.cache.transactional.TransactionalEntities.Post;
-import static com.vladmihalcea.book.hpjp.hibernate.cache.transactional.TransactionalEntities.PostComment;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = TransactionalCacheConcurrencyStrategyTestConfiguration.class)
-@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
-public class TransactionalCacheConcurrencyStrategyTest extends AbstractTest {
-
- protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
-
- @PersistenceContext
- private EntityManager entityManager;
-
- @Autowired
- private TransactionTemplate transactionTemplate;
-
- @Override
- protected void doInJPA(JPATransactionVoidFunction function) {
- transactionTemplate.execute((TransactionCallback) status -> {
- function.accept(entityManager);
- return null;
- });
- }
-
- @Before
- public void init() {
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("JDBC part review");
- post.addComment(comment1);
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Hibernate part review");
- post.addComment(comment2);
-
- entityManager.persist(post);
- });
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- LOGGER.info("Post entity inserted");
- }
-
- @Override
- public void destroy() {
-
- }
-
- @Override
- protected Class>[] entities() {
- return new Class>[0];
- }
-
- @Override
- public EntityManagerFactory entityManagerFactory() {
- return entityManager.getEntityManagerFactory();
- }
-
- @Test
- public void testPostEntityLoad() {
-
- LOGGER.info("Load Post entity and comments collection");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- printCacheRegionStatistics(post.getClass().getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- });
- }
-
- @Test
- public void testPostEntityEvictModifyLoad() {
-
- LOGGER.info("Evict, modify, load");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.detach(post);
-
- post.setTitle("High-Performance Hibernate");
- entityManager.merge(post);
- entityManager.flush();
-
- entityManager.detach(post);
- post = entityManager.find(Post.class, 1L);
- printCacheRegionStatistics(post.getClass().getName());
- });
- }
-
- @Test
- public void testEntityUpdate() {
- LOGGER.debug("testEntityUpdate");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- doInJPA(entityManager -> {
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- Post post = entityManager.find(Post.class, 1L);
- post.setTitle("High-Performance Hibernate");
- PostComment comment = post.getComments().remove(0);
- comment.setPost(null);
-
- entityManager.flush();
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- LOGGER.debug("Commit after flush");
- });
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
- }
-
- @Test
- public void testEntityUpdateWithRollback() {
- LOGGER.debug("testEntityUpdate");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- try {
- doInJPA(entityManager -> {
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- Post post = entityManager.find(Post.class, 1L);
- post.setTitle("High-Performance Hibernate");
- PostComment comment = post.getComments().remove(0);
- comment.setPost(null);
-
- entityManager.flush();
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- if(comment.getId() != null) {
- throw new IllegalStateException("Intentional roll back!");
- }
- });
- } catch (Exception expected) {
- LOGGER.info("Expected", expected);
- }
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
- }
-
- @Test
- public void testNonVersionedEntityUpdate() {
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L);
- });
- printCacheRegionStatistics(PostComment.class.getName());
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L);
- comment.setReview("JDBC and Database part review");
- });
- printCacheRegionStatistics(PostComment.class.getName());
- }
-
- @Test
- public void testEntityDelete() {
- LOGGER.info("Cache entries can be deleted");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.remove(post);
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertNull(post);
- });
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/TransactionalCacheConcurrencyStrategyTestConfiguration.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/TransactionalCacheConcurrencyStrategyTestConfiguration.java
deleted file mode 100644
index 8307ab0f9..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/TransactionalCacheConcurrencyStrategyTestConfiguration.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache.transactional;
-
-import com.vladmihalcea.book.hpjp.util.spring.config.jta.HsqldbJtaTransactionManagerConfiguration;
-import org.springframework.context.annotation.Configuration;
-
-import java.util.Properties;
-
-@Configuration
-public class TransactionalCacheConcurrencyStrategyTestConfiguration extends HsqldbJtaTransactionManagerConfiguration {
-
- @Override
- protected Properties additionalProperties() {
- Properties properties = super.additionalProperties();
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- properties.put("hibernate.generate_statistics", Boolean.TRUE.toString());
- return properties;
- }
-
- @Override
- protected Class configurationClass() {
- return TransactionalEntities.class;
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/identity/IdentityTransactionalCacheConcurrencyStrategyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/identity/IdentityTransactionalCacheConcurrencyStrategyTest.java
deleted file mode 100644
index 0adb94c9a..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/identity/IdentityTransactionalCacheConcurrencyStrategyTest.java
+++ /dev/null
@@ -1,176 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache.transactional.identity;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.vladmihalcea.book.hpjp.util.transaction.JPATransactionVoidFunction;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.transaction.support.TransactionCallback;
-import org.springframework.transaction.support.TransactionTemplate;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.PersistenceContext;
-
-import static com.vladmihalcea.book.hpjp.hibernate.cache.transactional.identity.IdentityTransactionalEntities.Post;
-import static com.vladmihalcea.book.hpjp.hibernate.cache.transactional.identity.IdentityTransactionalEntities.PostComment;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = IdentityTransactionalCacheConcurrencyStrategyTestConfiguration.class)
-@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
-public class IdentityTransactionalCacheConcurrencyStrategyTest extends AbstractTest {
-
- protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
-
- @PersistenceContext
- private EntityManager entityManager;
-
- @Autowired
- private TransactionTemplate transactionTemplate;
-
- @Override
- protected void doInJPA(JPATransactionVoidFunction function) {
- transactionTemplate.execute((TransactionCallback) status -> {
- function.accept(entityManager);
- return null;
- });
- }
-
- @Before
- public void init() {
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setTitle("High-Performance Java Persistence");
-
- PostComment comment1 = new PostComment();
- comment1.setReview("JDBC part review");
- post.addComment(comment1);
-
- PostComment comment2 = new PostComment();
- comment2.setReview("Hibernate part review");
- post.addComment(comment2);
-
- entityManager.persist(post);
- });
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- LOGGER.info("Post entity inserted");
- }
-
- @Override
- public void destroy() {
-
- }
-
- @Override
- protected Class>[] entities() {
- return new Class>[0];
- }
-
- @Override
- public EntityManagerFactory entityManagerFactory() {
- return entityManager.getEntityManagerFactory();
- }
-
- @Test
- public void testPostEntityLoad() {
-
- LOGGER.info("Load Post entity and comments collection");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- printCacheRegionStatistics(post.getClass().getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- });
- }
-
- @Test
- public void testPostEntityEvictModifyLoad() {
-
- LOGGER.info("Evict, modify, load");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.detach(post);
-
- post.setTitle("High-Performance Hibernate");
- entityManager.merge(post);
- entityManager.flush();
-
- entityManager.detach(post);
- post = entityManager.find(Post.class, 1L);
- printCacheRegionStatistics(post.getClass().getName());
- });
- }
-
- @Test
- public void testEntityUpdate() {
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- post.setTitle("High-Performance Hibernate");
- PostComment comment = post.getComments().remove(0);
- comment.setPost(null);
-
- entityManager.flush();
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- LOGGER.debug("Commit after flush");
- });
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
- }
-
- @Test
- public void testNonVersionedEntityUpdate() {
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L);
- });
- printCacheRegionStatistics(PostComment.class.getName());
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L);
- comment.setReview("JDBC and Database part review");
- });
- printCacheRegionStatistics(PostComment.class.getName());
- }
-
- @Test
- public void testEntityDelete() {
- LOGGER.info("Cache entries can be deleted");
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(2, post.getComments().size());
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.remove(post);
- });
-
- printCacheRegionStatistics(Post.class.getName());
- printCacheRegionStatistics(Post.class.getName() + ".comments");
- printCacheRegionStatistics(PostComment.class.getName());
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertNull(post);
- });
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/identity/IdentityTransactionalCacheConcurrencyStrategyTestConfiguration.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/identity/IdentityTransactionalCacheConcurrencyStrategyTestConfiguration.java
deleted file mode 100644
index 04afcd74d..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/transactional/identity/IdentityTransactionalCacheConcurrencyStrategyTestConfiguration.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.cache.transactional.identity;
-
-import com.vladmihalcea.book.hpjp.util.spring.config.jta.HsqldbJtaTransactionManagerConfiguration;
-import org.springframework.context.annotation.Configuration;
-
-import java.util.Properties;
-
-@Configuration
-public class IdentityTransactionalCacheConcurrencyStrategyTestConfiguration extends HsqldbJtaTransactionManagerConfiguration {
-
- @Override
- protected Properties additionalProperties() {
- Properties properties = super.additionalProperties();
- properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- properties.put("hibernate.generate_statistics", Boolean.TRUE.toString());
- return properties;
- }
-
- @Override
- protected Class configurationClass() {
- return IdentityTransactionalEntities.class;
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/CascadeLockTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/CascadeLockTest.java
deleted file mode 100644
index a2666daa7..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/CascadeLockTest.java
+++ /dev/null
@@ -1,451 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.concurrency;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.LockMode;
-import org.hibernate.LockOptions;
-import org.hibernate.Session;
-import org.hibernate.jpa.AvailableSettings;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
-
-/**
- * CascadeLockTest - Test to check CascadeType.LOCK
- *
- * @author Vlad Mihalcea
- */
-public class CascadeLockTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostDetails.class,
- PostComment.class
- };
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setTitle("Hibernate Master Class");
- entityManager.persist(post);
-
- post.addDetails(new PostDetails());
- post.addComment(new PostComment("Good post!"));
- post.addComment(new PostComment("Nice post!"));
- });
- }
-
- @Test
- public void testCascadeLockOnManagedEntityWithScope() throws InterruptedException {
- LOGGER.info("Test lock cascade for managed entity");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE))
- .setScope(true)
- .lock(post);
- });
- }
-
- @Test
- public void testCascadeLockOnManagedEntityWithJPA() throws InterruptedException {
- LOGGER.info("Test lock cascade for managed entity");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
- AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
- ));
- });
- }
-
- @Test
- public void testCascadeLockOnManagedEntityWithQuery() throws InterruptedException {
- LOGGER.info("Test lock cascade for managed entity");
- doInJPA(entityManager -> {
- Post post = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "join fetch p.comments " +
- "where p.id = :id", Post.class)
- .setParameter("id", 1L)
- .setLockMode(LockModeType.PESSIMISTIC_WRITE)
- .getSingleResult();
- });
- }
-
- @Test
- public void testCascadeLockOnManagedEntityWithAssociationsInitialzied() throws InterruptedException {
- LOGGER.info("Test lock cascade for managed entity");
- doInJPA(entityManager -> {
- Session session = entityManager.unwrap(Session.class);
- Post post = (Post) entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "join fetch p.comments " +
- "where " +
- " p.id = :id"
- ).setParameter("id", 1L)
- .getSingleResult();
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).setScope(true).lock(post);
- });
- }
-
- @Test
- public void testCascadeLockOnManagedEntityWithAssociationsInitializedAndJpa() throws InterruptedException {
- LOGGER.info("Test lock cascade for managed entity");
- doInJPA(entityManager -> {
- Post post = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "where p.id = :id", Post.class)
- .setParameter("id", 1L)
- .getSingleResult();
- entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
- AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
- ));
- });
- }
-
- private void containsPost(EntityManager entityManager, Post post, boolean expected) {
- assertEquals(expected, entityManager.contains(post));
- assertEquals(expected, (entityManager.contains(post.getDetails())));
- for(PostComment comment : post.getComments()) {
- assertEquals(expected, (entityManager.contains(comment)));
- }
- }
-
- @Test
- public void testCascadeLockOnDetachedEntityWithoutScope() {
- LOGGER.info("Test lock cascade for detached entity without scope");
-
- //Load the Post entity, which will become detached
- Post post = doInJPA(entityManager ->
- (Post) entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "join fetch p.comments " +
- "where p.id = :id"
- ).setParameter("id", 1L)
- .getSingleResult());
-
- //Change the detached entity state
- post.setTitle("Hibernate Training");
- doInJPA(entityManager -> {
- Session session = entityManager.unwrap(Session.class);
- //The Post entity graph is detached
- containsPost(entityManager, post, false);
-
- //The Lock request associates the entity graph and locks the requested entity
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).lock(post);
-
- //Hibernate doesn't know if the entity is dirty
- assertEquals("Hibernate Training", post.getTitle());
-
- //The Post entity graph is attached
- containsPost(entityManager, post, true);
- });
- doInJPA(entityManager -> {
- //The detached Post entity changes have been lost
- Post _post = (Post) entityManager.find(Post.class, 1L);
- assertEquals("Hibernate Master Class", _post.getTitle());
- });
- }
-
- @Test
- public void testCascadeLockOnDetachedEntityWithScope() {
- LOGGER.info("Test lock cascade for detached entity with scope");
-
- //Load the Post entity, which will become detached
- Post post = doInJPA(entityManager -> {
- return entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "join fetch p.comments " +
- "where p.id = :id", Post.class)
- .setParameter("id", 1L)
- .getSingleResult();
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("Reattach and lock");
- entityManager.unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE))
- .setScope(true)
- .lock(post);
-
- //The Post entity graph is attached
- containsPost(entityManager, post, true);
- });
- doInJPA(entityManager -> {
- //The detached Post entity changes have been lost
- Post _post = (Post) entityManager.find(Post.class, 1L);
- assertEquals("Hibernate Master Class", _post.getTitle());
- });
- }
-
- @Test
- public void testCascadeLockOnDetachedEntityUninitializedWithScope() {
- LOGGER.info("Test lock cascade for detached entity with scope");
-
- //Load the Post entity, which will become detached
- Post post = doInJPA(entityManager -> (Post) entityManager.find(Post.class, 1L));
-
- doInJPA(entityManager -> {
- LOGGER.info("Reattach and lock entity with associations not initialized");
- entityManager.unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE))
- .setScope(true)
- .lock(post);
-
- LOGGER.info("Check entities are reattached");
- //The Post entity graph is attached
- containsPost(entityManager, post, true);
- });
- }
-
- @Test
- public void testCascadeLockOnDetachedChildEntityUninitializedWithScope() {
- LOGGER.info("Test lock cascade for detached entity with scope");
-
- //Load the Post entity, which will become detached
- PostComment postComment = doInJPA(entityManager -> (PostComment) entityManager.find(PostComment.class, 3L));
-
- doInJPA(entityManager -> {
- LOGGER.info("Reattach and lock entity with associations not initialized");
- entityManager.unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE))
- .lock(postComment);
- });
- }
-
- @Test
- public void testUpdateOnDetachedEntity() {
- LOGGER.info("Test update for detached entity");
- //Load the Post entity, which will become detached
- Post post = doInJPA(entityManager -> (Post) entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "join fetch p.comments " +
- "where p.id = :id", Post.class)
- .setParameter("id", 1L)
- .getSingleResult());
-
- //Change the detached entity state
- post.setTitle("Hibernate Training");
-
- doInJPA(entityManager -> {
- Session session = entityManager.unwrap(Session.class);
- //The Post entity graph is detached
- containsPost(entityManager, post, false);
-
- //The update will trigger an entity state flush and attach the entity graph
- session.update(post);
-
- //The Post entity graph is attached
- containsPost(entityManager, post, true);
- });
- doInJPA(entityManager -> {
- Post _post = (Post) entityManager.find(Post.class, 1L);
- assertEquals("Hibernate Training", _post.getTitle());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- private String body;
-
- @Version
- private int version;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- @OneToOne(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true, fetch = FetchType.LAZY, optional = false)
- private PostDetails details;
-
- 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 List getComments() {
- return comments;
- }
-
- public PostDetails getDetails() {
- return details;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
-
- public void addDetails(PostDetails details) {
- this.details = details;
- details.setPost(this);
- }
-
- public void removeDetails() {
- this.details.setPost(null);
- this.details = null;
- }
- }
-
- @Entity(name = "PostDetails")
- @Table(name = "post_details")
- public static class PostDetails {
-
- @Id
- private Long id;
-
- @Column(name = "created_on")
- private Date createdOn;
-
- @Column(name = "created_by")
- private String createdBy;
-
- @Version
- private int version;
-
- public PostDetails() {
- createdOn = new Date();
- }
-
- @OneToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "id")
- @MapsId
- private Post post;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public Date getCreatedOn() {
- return createdOn;
- }
-
- public void setCreatedOn(Date createdOn) {
- this.createdOn = createdOn;
- }
-
- public String getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- @Version
- private int version;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/CascadeLockUnidirectionalOneToManyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/CascadeLockUnidirectionalOneToManyTest.java
deleted file mode 100644
index ac1080d07..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/CascadeLockUnidirectionalOneToManyTest.java
+++ /dev/null
@@ -1,437 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.concurrency;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.LockMode;
-import org.hibernate.LockOptions;
-import org.hibernate.Session;
-import org.hibernate.jpa.AvailableSettings;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
-
-/**
- * CascadeLockTest - Test to check CascadeType.LOCK
- *
- * @author Vlad Mihalcea
- */
-public class CascadeLockUnidirectionalOneToManyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostDetails.class,
- PostComment.class
- };
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setTitle("Hibernate Master Class");
- entityManager.persist(post);
-
- post.addDetails(new PostDetails());
- post.addComment(new PostComment("Good post!"));
- post.addComment(new PostComment("Nice post!"));
- });
- }
-
- @Test
- public void testCascadeLockOnManagedEntityWithScope() throws InterruptedException {
- LOGGER.info("Test lock cascade for managed entity");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE))
- .setScope(true)
- .lock(post);
- });
- }
-
- @Test
- public void testCascadeLockOnManagedEntityWithJPA() throws InterruptedException {
- LOGGER.info("Test lock cascade for managed entity");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
- AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
- ));
- });
- }
-
- @Test
- public void testCascadeLockOnManagedEntityWithQuery() throws InterruptedException {
- LOGGER.info("Test lock cascade for managed entity");
- doInJPA(entityManager -> {
- Post post = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "join fetch p.comments " +
- "where p.id = :id", Post.class)
- .setParameter("id", 1L)
- .setLockMode(LockModeType.PESSIMISTIC_WRITE)
- .getSingleResult();
- });
- }
-
- @Test
- public void testCascadeLockOnManagedEntityWithAssociationsInitialzied() throws InterruptedException {
- LOGGER.info("Test lock cascade for managed entity");
- doInJPA(entityManager -> {
- Session session = entityManager.unwrap(Session.class);
- Post post = (Post) entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "join fetch p.comments " +
- "where " +
- " p.id = :id"
- ).setParameter("id", 1L)
- .getSingleResult();
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).setScope(true).lock(post);
- });
- }
-
- @Test
- public void testCascadeLockOnManagedEntityWithAssociationsInitializedAndJpa() throws InterruptedException {
- LOGGER.info("Test lock cascade for managed entity");
- doInJPA(entityManager -> {
- Post post = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "where p.id = :id", Post.class)
- .setParameter("id", 1L)
- .getSingleResult();
- entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
- AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
- ));
- });
- }
-
- private void containsPost(EntityManager entityManager, Post post, boolean expected) {
- assertEquals(expected, entityManager.contains(post));
- assertEquals(expected, (entityManager.contains(post.getDetails())));
- for(PostComment comment : post.getComments()) {
- assertEquals(expected, (entityManager.contains(comment)));
- }
- }
-
- @Test
- public void testCascadeLockOnDetachedEntityWithoutScope() {
- LOGGER.info("Test lock cascade for detached entity without scope");
-
- //Load the Post entity, which will become detached
- Post post = doInJPA(entityManager ->
- (Post) entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "join fetch p.comments " +
- "where p.id = :id"
- ).setParameter("id", 1L)
- .getSingleResult());
-
- //Change the detached entity state
- post.setTitle("Hibernate Training");
- doInJPA(entityManager -> {
- Session session = entityManager.unwrap(Session.class);
- //The Post entity graph is detached
- containsPost(entityManager, post, false);
-
- //The Lock request associates the entity graph and locks the requested entity
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).lock(post);
-
- //Hibernate doesn't know if the entity is dirty
- assertEquals("Hibernate Training", post.getTitle());
-
- //The Post entity graph is attached
- containsPost(entityManager, post, true);
- });
- doInJPA(entityManager -> {
- //The detached Post entity changes have been lost
- Post _post = (Post) entityManager.find(Post.class, 1L);
- assertEquals("Hibernate Master Class", _post.getTitle());
- });
- }
-
- @Test
- public void testCascadeLockOnDetachedEntityWithScope() {
- LOGGER.info("Test lock cascade for detached entity with scope");
-
- //Load the Post entity, which will become detached
- Post post = doInJPA(entityManager -> (Post) entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "join fetch p.comments " +
- "where p.id = :id", Post.class)
- .setParameter("id", 1L)
- .getSingleResult());
-
- doInJPA(entityManager -> {
- LOGGER.info("Reattach and lock");
- entityManager.unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE))
- .setScope(true)
- .lock(post);
-
- //The Post entity graph is attached
- containsPost(entityManager, post, true);
- });
- doInJPA(entityManager -> {
- //The detached Post entity changes have been lost
- Post _post = (Post) entityManager.find(Post.class, 1L);
- assertEquals("Hibernate Master Class", _post.getTitle());
- });
- }
-
- @Test
- public void testCascadeLockOnDetachedEntityUninitializedWithScope() {
- LOGGER.info("Test lock cascade for detached entity with scope");
-
- //Load the Post entity, which will become detached
- Post post = doInJPA(entityManager -> (Post) entityManager.find(Post.class, 1L));
-
- doInJPA(entityManager -> {
- LOGGER.info("Reattach and lock entity with associations not initialized");
- entityManager.unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE))
- .setScope(true)
- .lock(post);
-
- LOGGER.info("Check entities are reattached");
- //The Post entity graph is attached
- containsPost(entityManager, post, true);
- });
- }
-
- @Test
- public void testCascadeLockOnDetachedChildEntityUninitializedWithScope() {
- LOGGER.info("Test lock cascade for detached entity with scope");
-
- //Load the Post entity, which will become detached
- PostComment postComment = doInJPA(entityManager -> (PostComment) entityManager.find(PostComment.class, 3L));
-
- doInJPA(entityManager -> {
- LOGGER.info("Reattach and lock entity with associations not initialized");
- entityManager.unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE))
- .lock(postComment);
- });
- }
-
- @Test
- public void testUpdateOnDetachedEntity() {
- LOGGER.info("Test update for detached entity");
- //Load the Post entity, which will become detached
- Post post = doInJPA(entityManager -> (Post) entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.details " +
- "join fetch p.comments " +
- "where p.id = :id", Post.class)
- .setParameter("id", 1L)
- .getSingleResult());
-
- //Change the detached entity state
- post.setTitle("Hibernate Training");
-
- doInJPA(entityManager -> {
- Session session = entityManager.unwrap(Session.class);
- //The Post entity graph is detached
- containsPost(entityManager, post, false);
-
- //The update will trigger an entity state flush and attach the entity graph
- session.update(post);
-
- //The Post entity graph is attached
- containsPost(entityManager, post, true);
- });
- doInJPA(entityManager -> {
- Post _post = (Post) entityManager.find(Post.class, 1L);
- assertEquals("Hibernate Training", _post.getTitle());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- private String body;
-
- @Version
- private int version;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- @OneToOne(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true, fetch = FetchType.LAZY, optional = false)
- private PostDetails details;
-
- 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 List getComments() {
- return comments;
- }
-
- public PostDetails getDetails() {
- return details;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- }
-
- public void addDetails(PostDetails details) {
- this.details = details;
- details.setPost(this);
- }
-
- public void removeDetails() {
- this.details.setPost(null);
- this.details = null;
- }
- }
-
- @Entity(name = "PostDetails")
- @Table(name = "post_details")
- public static class PostDetails {
-
- @Id
- private Long id;
-
- @Column(name = "created_on")
- private Date createdOn;
-
- @Column(name = "created_by")
- private String createdBy;
-
- @Version
- private int version;
-
- public PostDetails() {
- createdOn = new Date();
- }
-
- @OneToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "id")
- @MapsId
- private Post post;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public Date getCreatedOn() {
- return createdOn;
- }
-
- public void setCreatedOn(Date createdOn) {
- this.createdOn = createdOn;
- }
-
- public String getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String review;
-
- @Version
- private int version;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/DefaultOptimisticLockingTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/DefaultOptimisticLockingTest.java
deleted file mode 100644
index 460493366..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/DefaultOptimisticLockingTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.concurrency;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.StaleStateException;
-import org.junit.Test;
-
-import javax.persistence.*;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Vlad Mihalcea
- */
-public class DefaultOptimisticLockingTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class
- };
- }
-
- @Test
- public void testOptimisticLocking() {
-
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
- entityManager.persist(post);
-
- entityManager.flush();
- post.setTitle("High-Performance Hibernate");
- });
-
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertEquals(1, post.getVersion());
- });
- }
-
- @Test
- public void testStaleStateException() {
-
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
- entityManager.persist(post);
- });
-
- try {
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
-
- executeSync(() -> {
- doInJPA(_entityManager -> {
- Post _post = _entityManager.find(Post.class, 1L);
- _post.setTitle("High-Performance JDBC");
- });
- });
-
- post.setTitle("High-Performance Hibernate");
- });
- } catch (Exception expected) {
- LOGGER.error("Throws", expected);
- assertEquals(OptimisticLockException.class, expected.getCause().getClass());
- assertEquals(StaleStateException.class, expected.getCause().getCause().getClass());
- }
- }
-
- @Entity(name = "Post") @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private int version;
-
- 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 int getVersion() {
- return version;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/LockModePessimisticReadWriteIntegrationTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/LockModePessimisticReadWriteIntegrationTest.java
deleted file mode 100644
index aa3cda701..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/LockModePessimisticReadWriteIntegrationTest.java
+++ /dev/null
@@ -1,312 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.concurrency;
-
-import com.vladmihalcea.book.hpjp.util.AbstractOracleXEIntegrationTest;
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.hibernate.LockMode;
-import org.hibernate.LockOptions;
-import org.hibernate.Session;
-import org.hibernate.StaleObjectStateException;
-import org.hibernate.dialect.lock.PessimisticEntityLockException;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.Collections;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-
-/**
- * LockModePessimisticReadWriteIntegrationTest - Test to check LockMode.PESSIMISTIC_READ and LockMode.PESSIMISTIC_WRITE
- *
- * @author Vlad Mihalcea
- */
-public class LockModePessimisticReadWriteIntegrationTest extends AbstractPostgreSQLIntegrationTest {
-
- public static final int WAIT_MILLIS = 500;
-
- private interface LockRequestCallable {
- void lock(Session session, Post post);
- }
-
- private final CountDownLatch endLatch = new CountDownLatch(1);
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class
- };
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
- post.setBody("Chapter 17 summary");
- entityManager.persist(post);
- });
- }
-
- private void testPessimisticLocking(LockRequestCallable primaryLockRequestCallable, LockRequestCallable secondaryLockRequestCallable) {
- doInJPA(entityManager -> {
- try {
- Session session = entityManager.unwrap(Session.class);
- Post post = entityManager.find(Post.class, 1L);
- primaryLockRequestCallable.lock(session, post);
- executeAsync(
- () -> {
- doInJPA(_entityManager -> {
- Session _session = _entityManager.unwrap(Session.class);
- Post _post = _entityManager.find(Post.class, 1L);
- secondaryLockRequestCallable.lock(_session, _post);
- });
- },
- endLatch::countDown
- );
- sleep(WAIT_MILLIS);
- } catch (StaleObjectStateException e) {
- LOGGER.info("Optimistic locking failure: ", e);
- }
- });
- awaitOnLatch(endLatch);
- }
-
- @Test
- public void testPessimisticRead() {
- LOGGER.info("Test PESSIMISTIC_READ");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L, LockModeType.PESSIMISTIC_READ);
- });
- }
-
- @Test
- public void testPessimisticWrite() {
- LOGGER.info("Test PESSIMISTIC_WRITE");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L, LockModeType.PESSIMISTIC_WRITE);
- });
- }
-
- @Test
- public void testPessimisticWriteAfterFetch() {
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE);
- });
- }
-
- @Test
- public void testPessimisticWriteAfterFetchWithDetachedForJPA() {
- Post post = doInJPA(entityManager -> {
- return entityManager.find(Post.class, 1L);
- });
- try {
- doInJPA(entityManager -> {
- entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE);
- });
- } catch (IllegalArgumentException e) {
- assertEquals("entity not in the persistence context", e.getMessage());
- }
- }
-
- @Test
- public void testPessimisticWriteAfterFetchWithDetachedForHibernate() {
- Post post = doInJPA(entityManager -> {
- return entityManager.find(Post.class, 1L);
- });
- doInJPA(entityManager -> {
- LOGGER.info("Lock and reattach");
- entityManager.unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE))
- .lock(post);
- post.setTitle("High-Performance Hibernate");
- });
- }
-
- @Test
- public void testPessimisticReadDoesNotBlockPessimisticRead() throws InterruptedException {
- LOGGER.info("Test PESSIMISTIC_READ doesn't block PESSIMISTIC_READ");
- testPessimisticLocking(
- (session, post) -> {
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_READ)).lock(post);
- LOGGER.info("PESSIMISTIC_READ acquired");
- },
- (session, post) -> {
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_READ)).lock(post);
- LOGGER.info("PESSIMISTIC_READ acquired");
- }
- );
- }
-
- @Test
- public void testPessimisticReadBlocksUpdate() throws InterruptedException {
- LOGGER.info("Test PESSIMISTIC_READ blocks UPDATE");
- testPessimisticLocking(
- (session, post) -> {
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_READ)).lock(post);
- LOGGER.info("PESSIMISTIC_READ acquired");
- },
- (session, post) -> {
- post.setBody("Chapter 16 summary");
- session.flush();
- LOGGER.info("Implicit lock acquired");
- }
- );
- }
-
- @Test
- public void testPessimisticReadWithPessimisticWriteNoWait() throws InterruptedException {
- LOGGER.info("Test PESSIMISTIC_READ blocks PESSIMISTIC_WRITE, NO WAIT fails fast");
- testPessimisticLocking(
- (session, post) -> {
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_READ)).lock(post);
- LOGGER.info("PESSIMISTIC_READ acquired");
- },
- (session, post) -> {
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).setTimeOut(Session.LockRequest.PESSIMISTIC_NO_WAIT).lock(post);
- LOGGER.info("PESSIMISTIC_WRITE acquired");
- }
- );
- }
-
- @Test
- public void testPessimisticWriteBlocksPessimisticRead() throws InterruptedException {
- LOGGER.info("Test PESSIMISTIC_WRITE blocks PESSIMISTIC_READ");
- testPessimisticLocking(
- (session, post) -> {
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).lock(post);
- LOGGER.info("PESSIMISTIC_WRITE acquired");
- },
- (session, post) -> {
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_READ)).lock(post);
- LOGGER.info("PESSIMISTIC_READ acquired");
- }
- );
- }
-
- @Test
- public void testPessimisticWriteBlocksPessimisticWrite() throws InterruptedException {
- LOGGER.info("Test PESSIMISTIC_WRITE blocks PESSIMISTIC_WRITE");
- testPessimisticLocking(
- (session, post) -> {
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).lock(post);
- LOGGER.info("PESSIMISTIC_WRITE acquired");
- },
- (session, post) -> {
- session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).lock(post);
- LOGGER.info("PESSIMISTIC_WRITE acquired");
- }
- );
- }
-
- @Test
- public void testPessimisticNoWait() {
- LOGGER.info("Test PESSIMISTIC_READ blocks PESSIMISTIC_WRITE, NO WAIT fails fast");
- Post post = doInJPA(entityManager -> {
- return entityManager.find(Post.class, 1L);
- });
-
- doInJPA(entityManager -> {
- entityManager.unwrap( Session.class ).lock(post, LockMode.PESSIMISTIC_WRITE);
-
- executeSync( () -> {
- doInJPA(_entityManager -> {
- try {
- _entityManager
- .unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE)
- .setTimeOut(LockOptions.NO_WAIT))
- .lock(post);
- fail("Should throw PessimisticEntityLockException");
- }
- catch (PessimisticEntityLockException expected) {
- //This is expected since the first transaction already acquired this lock
- }
- });
- } );
- });
- }
-
- @Test
- public void testPessimisticNoWaitJPA() throws InterruptedException {
- LOGGER.info("Test PESSIMISTIC_READ blocks PESSIMISTIC_WRITE, NO WAIT fails fast");
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE,
- Collections.singletonMap("javax.persistence.lock.timeout", 0)
- );
- });
- }
-
- @Test
- public void testPessimisticTimeout() throws InterruptedException {
- doInJPA(entityManager -> {
- Post post = entityManager.getReference(Post.class, 1L);
-
- entityManager.unwrap(Session.class)
- .buildLockRequest(
- new LockOptions(LockMode.PESSIMISTIC_WRITE)
- .setTimeOut((int) TimeUnit.SECONDS.toMillis(3)))
- .lock(post);
- });
- }
-
- @Test
- public void testPessimisticTimeoutJPA() throws InterruptedException {
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE,
- Collections.singletonMap("javax.persistence.lock.timeout",
- TimeUnit.SECONDS.toMillis(3))
- );
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- private String body;
-
- @Version
- private int version;
-
- 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 getBody() {
- return body;
- }
-
- public void setBody(String body) {
- this.body = body;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/OptimisticLockingChildUpdatesRootVersionTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/OptimisticLockingChildUpdatesRootVersionTest.java
deleted file mode 100644
index e327af2dc..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/OptimisticLockingChildUpdatesRootVersionTest.java
+++ /dev/null
@@ -1,336 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.concurrency;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.HibernateException;
-import org.hibernate.LockMode;
-import org.hibernate.boot.Metadata;
-import org.hibernate.engine.spi.EntityEntry;
-import org.hibernate.engine.spi.SessionFactoryImplementor;
-import org.hibernate.engine.spi.SessionImplementor;
-import org.hibernate.engine.spi.Status;
-import org.hibernate.event.service.spi.EventListenerRegistry;
-import org.hibernate.event.spi.*;
-import org.hibernate.integrator.spi.Integrator;
-import org.hibernate.persister.entity.EntityPersister;
-import org.hibernate.service.spi.SessionFactoryServiceRegistry;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.persistence.*;
-import java.util.Map;
-
-/**
- * @author Vlad Mihalcea
- */
-public class OptimisticLockingChildUpdatesRootVersionTest extends AbstractTest {
-
- public static class RootAwareEventListenerIntegrator implements org.hibernate.integrator.spi.Integrator {
-
- public static final RootAwareEventListenerIntegrator INSTANCE = new RootAwareEventListenerIntegrator();
-
- @Override
- public void integrate(
- Metadata metadata,
- SessionFactoryImplementor sessionFactory,
- SessionFactoryServiceRegistry serviceRegistry) {
-
- final EventListenerRegistry eventListenerRegistry =
- serviceRegistry.getService( EventListenerRegistry.class );
-
- eventListenerRegistry.appendListeners(EventType.PERSIST, RootAwareInsertEventListener.INSTANCE);
- eventListenerRegistry.appendListeners(EventType.FLUSH_ENTITY, RootAwareUpdateAndDeleteEventListener.INSTANCE);
- }
-
- @Override
- public void disintegrate(
- SessionFactoryImplementor sessionFactory,
- SessionFactoryServiceRegistry serviceRegistry) {
-
- }
- }
-
- public static class RootAwareInsertEventListener implements PersistEventListener {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(RootAwareInsertEventListener.class);
-
- public static final RootAwareInsertEventListener INSTANCE = new RootAwareInsertEventListener();
-
- @Override
- public void onPersist(PersistEvent event) throws HibernateException {
- final Object entity = event.getObject();
-
- if(entity instanceof RootAware) {
- RootAware rootAware = (RootAware) entity;
- Object root = rootAware.root();
- event.getSession().lock(root, LockMode.OPTIMISTIC_FORCE_INCREMENT);
-
- LOGGER.info("Incrementing {} entity version because a {} child entity has been inserted", root, entity);
- }
- }
-
- @Override
- public void onPersist(PersistEvent event, Map createdAlready) throws HibernateException {
- onPersist(event);
- }
- }
-
- public static class RootAwareUpdateAndDeleteEventListener implements FlushEntityEventListener {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(RootAwareUpdateAndDeleteEventListener.class);
-
- public static final RootAwareUpdateAndDeleteEventListener INSTANCE = new RootAwareUpdateAndDeleteEventListener();
-
- @Override
- public void onFlushEntity(FlushEntityEvent event) throws HibernateException {
- final EntityEntry entry = event.getEntityEntry();
- final Object entity = event.getEntity();
- final boolean mightBeDirty = entry.requiresDirtyCheck( entity );
-
- if(mightBeDirty && entity instanceof RootAware) {
- RootAware rootAware = (RootAware) entity;
- if(updated(event)) {
- Object root = rootAware.root();
- LOGGER.info("Incrementing {} entity version because a {} child entity has been updated", root, entity);
- incrementRootVersion(event, root);
- }
- else if (deleted(event)) {
- Object root = rootAware.root();
- LOGGER.info("Incrementing {} entity version because a {} child entity has been deleted", root, entity);
- incrementRootVersion(event, root);
- }
- }
- }
-
- private void incrementRootVersion(FlushEntityEvent event, Object root) {
- event.getSession().lock(root, LockMode.OPTIMISTIC_FORCE_INCREMENT);
- }
-
- private boolean deleted(FlushEntityEvent event) {
- return event.getEntityEntry().getStatus() == Status.DELETED;
- }
-
- private boolean updated(FlushEntityEvent event) {
- final EntityEntry entry = event.getEntityEntry();
- final Object entity = event.getEntity();
-
- int[] dirtyProperties;
- EntityPersister persister = entry.getPersister();
- final Object[] values = event.getPropertyValues();
- SessionImplementor session = event.getSession();
-
- if ( event.hasDatabaseSnapshot() ) {
- dirtyProperties = persister.findModified( event.getDatabaseSnapshot(), values, entity, session );
- }
- else {
- dirtyProperties = persister.findDirty( values, entry.getLoadedState(), entity, session );
- }
-
- return dirtyProperties != null;
- }
- }
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- PostCommentDetails.class,
- };
- }
-
- @Override
- protected Integrator integrator() {
- return RootAwareEventListenerIntegrator.INSTANCE;
- }
-
- @Test
- public void test() {
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
-
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("Good");
- comment1.setPost(post);
-
- PostCommentDetails details1 = new PostCommentDetails();
- details1.setComment(comment1);
- details1.setVotes(10);
-
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Excellent");
- comment2.setPost(post);
-
- PostCommentDetails details2 = new PostCommentDetails();
- details2.setComment(comment2);
- details2.setVotes(10);
-
- entityManager.persist(post);
- entityManager.persist(comment1);
- entityManager.persist(comment2);
- entityManager.persist(details1);
- entityManager.persist(details2);
- });
-
- doInJPA(entityManager -> {
- PostCommentDetails postCommentDetails = entityManager.createQuery(
- "select pcd " +
- "from PostCommentDetails pcd " +
- "join fetch pcd.comment pc " +
- "join fetch pc.post p " +
- "where pcd.id = :id", PostCommentDetails.class)
- .setParameter("id", 2L)
- .getSingleResult();
-
- postCommentDetails.setVotes(15);
- });
-
- doInJPA(entityManager -> {
- PostComment postComment = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "join fetch pc.post p " +
- "where pc.id = :id", PostComment.class)
- .setParameter("id", 2L)
- .getSingleResult();
-
- postComment.setReview("Brilliant!");
- });
-
- doInJPA(entityManager -> {
- Post post = entityManager.getReference(Post.class, 1L);
-
- PostComment postComment = new PostComment();
- postComment.setId(3L);
- postComment.setReview("Worth it!");
- postComment.setPost(post);
- entityManager.persist(postComment);
- });
-
- doInJPA(entityManager -> {
- PostComment postComment = entityManager.getReference(PostComment.class, 3l);
- entityManager.remove(postComment);
- });
- }
-
- public interface RootAware {
- T root();
- }
-
- @Entity(name = "Post") @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @Version
- private Integer version;
-
- 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;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment implements RootAware {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
-
- @Override
- public Post root() {
- return post;
- }
- }
-
- @Entity(name = "PostCommentDetails")
- @Table(name = "post_comment_details")
- public static class PostCommentDetails implements RootAware {
-
- @Id
- private Long id;
-
- @OneToOne(fetch = FetchType.LAZY)
- @MapsId
- private PostComment comment;
-
- private int votes;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public PostComment getComment() {
- return comment;
- }
-
- public void setComment(PostComment comment) {
- this.comment = comment;
- }
-
- public int getVotes() {
- return votes;
- }
-
- public void setVotes(int votes) {
- this.votes = votes;
- }
-
- @Override
- public Post root() {
- return comment.root();
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/SkipLockJobQueueTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/SkipLockJobQueueTest.java
deleted file mode 100644
index 936639eba..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/concurrency/SkipLockJobQueueTest.java
+++ /dev/null
@@ -1,236 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.concurrency;
-
-import com.vladmihalcea.book.hpjp.util.AbstractOracleXEIntegrationTest;
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.apache.commons.lang.exception.ExceptionUtils;
-import org.hibernate.LockMode;
-import org.hibernate.LockOptions;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-
-/**
- * @author Vlad Mihalcea
- */
-public class SkipLockJobQueueTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class
- };
- }
-
- @Before
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- for (long i = 0; i < 10; i++) {
- Post post = new Post();
- post.setId(i);
- post.setTitle("High-Performance Java Persistence");
- post.setBody(String.format("Chapter %d summary", i));
- post.setStatus(PostStatus.PENDING);
- entityManager.persist(post);
- }
- });
- }
-
- @Test
- public void testLockContention() {
- LOGGER.info("Test lock contention");
- doInJPA(entityManager -> {
- List pendingPosts = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "where p.status = :status",
- Post.class)
- .setParameter("status", PostStatus.PENDING)
- .setFirstResult(0)
- .setMaxResults(2)
- .setLockMode(LockModeType.PESSIMISTIC_WRITE)
- .setHint("javax.persistence.lock.timeout", 0)
- .getResultList();
-
- assertEquals(2, pendingPosts.size());
-
- try {
- executeSync(() -> {
- doInJPA(_entityManager -> {
- List _pendingPosts = _entityManager.createQuery(
- "select p " +
- "from Post p " +
- "where p.status = :status", Post.class)
- .setParameter("status", PostStatus.PENDING)
- .setFirstResult(0)
- .setMaxResults(2)
- .setLockMode(LockModeType.PESSIMISTIC_WRITE)
- .setHint("javax.persistence.lock.timeout", 0)
- .getResultList();
- });
- });
- } catch (Exception e) {
- assertEquals(1, Arrays.asList(ExceptionUtils.getThrowables(e))
- .stream()
- .map(Throwable::getClass)
- .filter(clazz -> clazz.equals(PessimisticLockException.class))
- .count());
- }
- });
- }
-
- @Test
- public void testSkipLocked() {
- LOGGER.info("Test lock contention");
- doInJPA(entityManager -> {
- final int lockCount = 2;
- LOGGER.debug("Alice wants to moderate {} Post(s)", lockCount);
- List pendingPosts = pendingPosts(entityManager, lockCount);
- List ids = pendingPosts.stream().map(Post::getId).collect(toList());
- assertTrue(ids.size() == 2 && ids.contains(0L) && ids.contains(1L));
-
- executeSync(() -> {
- doInJPA(_entityManager -> {
- LOGGER.debug("Bob wants to moderate {} Post(s)", lockCount);
- List _pendingPosts = pendingPosts(_entityManager, lockCount);
- List _ids = _pendingPosts.stream().map(Post::getId).collect(toList());
- assertTrue(_ids.size() == 2 && _ids.contains(2L) && _ids.contains(3L));
- });
- });
- });
- }
-
- @Test
- public void testAliceLocksAll() {
- LOGGER.info("Test lock contention");
- doInJPA(entityManager -> {
- List pendingPosts = pendingPosts(entityManager, 10);
- assertTrue(pendingPosts.size() == 10);
-
- executeSync(() -> {
- doInJPA(_entityManager -> {
- List _pendingPosts = pendingPosts(_entityManager, 2);
- assertTrue(_pendingPosts.size() == 0);
- });
- });
- });
- }
-
- @Test
- public void testSkipLockedMaxCountLessThanLockCount() {
- LOGGER.info("Test lock contention");
- doInJPA(entityManager -> {
- List pendingPosts = pendingPosts(entityManager, 11);
- assertEquals(10, pendingPosts.size());
- });
- }
-
- public List pendingPosts(EntityManager entityManager, int lockCount) {
- return pendingPosts(entityManager, lockCount, lockCount, null);
- }
-
- private List pendingPosts(EntityManager entityManager, int lockCount,
- int maxResults, Integer maxCount) {
- LOGGER.debug("Attempting to lock {} Post(s) entities", maxResults);
- List posts= entityManager.createQuery(
- "select p from Post p where p.status = :status", Post.class)
- .setParameter("status", PostStatus.PENDING)
- .setMaxResults(maxResults)
- .unwrap(org.hibernate.query.Query.class)
- //Legacy hack - UPGRADE_SKIPLOCKED bypasses follow-on-locking
- //.setLockOptions(new LockOptions(LockMode.UPGRADE_SKIPLOCKED))
- .setLockOptions(new LockOptions(LockMode.PESSIMISTIC_WRITE)
- .setTimeOut(LockOptions.SKIP_LOCKED)
- //This is not really needed for this query but shows that you can control the follow-on locking mechanism
- .setFollowOnLocking(false)
- )
- .list();
-
- if(posts.isEmpty()) {
- if(maxCount == null) {
- maxCount = pendingPostCount(entityManager);
- }
- if(maxResults < maxCount || maxResults == lockCount) {
- maxResults += lockCount;
- return pendingPosts(entityManager, lockCount, maxResults, maxCount);
- }
- }
- LOGGER.debug("{} Post(s) entities have been locked", posts.size());
- return posts;
- }
-
- private int pendingPostCount(EntityManager entityManager) {
- int postCount = ((Number) entityManager.createQuery(
- "select count(*) from Post where status = :status")
- .setParameter("status", PostStatus.PENDING)
- .getSingleResult()).intValue();
-
- LOGGER.debug("There are {} PENDING Post(s)", postCount);
- return postCount;
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- private String body;
-
- @Enumerated
- private PostStatus status;
-
- @Version
- private int version;
-
- 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 getBody() {
- return body;
- }
-
- public void setBody(String body) {
- this.body = body;
- }
-
- public PostStatus getStatus() {
- return status;
- }
-
- public void setStatus(PostStatus status) {
- this.status = status;
- }
- }
-
- public enum PostStatus {
- PENDING,
- APPROVED,
- SPAM
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/C3P0CockroachDBConnectionProviderTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/C3P0CockroachDBConnectionProviderTest.java
deleted file mode 100644
index da8869ccd..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/C3P0CockroachDBConnectionProviderTest.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import java.util.Properties;
-
-import com.vladmihalcea.book.hpjp.util.providers.CockroachDBDataSourceProvider;
-import com.vladmihalcea.book.hpjp.util.providers.DataSourceProvider;
-
-public class C3P0CockroachDBConnectionProviderTest extends JPADriverConnectionProviderTest {
-
- protected DataSourceProvider dataSourceProvider() {
- return new CockroachDBDataSourceProvider();
- }
-
- @Override
- protected void appendDriverProperties(Properties properties) {
- super.appendDriverProperties(properties);
- properties.put("hibernate.c3p0.min_size", 1);
- properties.put("hibernate.c3p0.max_size", 5);
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/C3P0ConnectionProviderTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/C3P0ConnectionProviderTest.java
deleted file mode 100644
index 707edee34..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/C3P0ConnectionProviderTest.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import java.util.Properties;
-
-public class C3P0ConnectionProviderTest extends JPADriverConnectionProviderTest {
-
- @Override
- protected void appendDriverProperties(Properties properties) {
- super.appendDriverProperties(properties);
- properties.put("hibernate.c3p0.min_size", 1);
- properties.put("hibernate.c3p0.max_size", 5);
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/C3P0JPAConnectionProviderTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/C3P0JPAConnectionProviderTest.java
deleted file mode 100644
index babad3967..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/C3P0JPAConnectionProviderTest.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import java.util.Properties;
-
-public class C3P0JPAConnectionProviderTest extends DriverConnectionProviderTest {
-
- @Override
- protected void appendDriverProperties(Properties properties) {
- super.appendDriverProperties(properties);
- properties.put("hibernate.c3p0.min_size", 1);
- properties.put("hibernate.c3p0.max_size", 5);
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/DriverConnectionProviderTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/DriverConnectionProviderTest.java
deleted file mode 100644
index b73886ad8..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/DriverConnectionProviderTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider;
-import com.vladmihalcea.book.hpjp.util.providers.DataSourceProvider;
-
-import org.junit.Test;
-
-import javax.sql.DataSource;
-import java.util.Properties;
-import java.util.concurrent.atomic.AtomicLong;
-
-import static com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider.Post;
-import static com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider.PostComment;
-
-public class DriverConnectionProviderTest extends AbstractTest {
-
- private BlogEntityProvider entityProvider = new BlogEntityProvider();
-
- @Override
- protected Class>[] entities() {
- return entityProvider.entities();
- }
-
- protected DataSource newDataSource() {
- return null;
- }
-
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.hbm2ddl.auto", "update");
- appendDriverProperties(properties);
- return properties;
- }
-
- protected void appendDriverProperties(Properties properties) {
- DataSourceProvider dataSourceProvider = dataSourceProvider();
- properties.put("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
- properties.put("hibernate.connection.url", dataSourceProvider.url());
- properties.put("hibernate.connection.username", dataSourceProvider.username());
- properties.put("hibernate.connection.password", dataSourceProvider.password());
- }
-
- @Test
- public void testConnection() {
- for (final AtomicLong i = new AtomicLong(); i.get() < 5; i.incrementAndGet()) {
- doInJPA(em -> {
- em.persist(new Post(i.get()));
- });
- }
-
- doInJPA(em -> {
- Post post = em.find(Post.class, 1L);
- PostComment comment = new PostComment("abc");
- comment.setId(1L);
- post.addComment(comment);
- em.persist(comment);
- });
- doInJPA(em -> {
- em.createQuery("select p from Post p join fetch p.comments", Post.class).getResultList();
- });
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/ExternalDataSourceConnectionProviderTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/ExternalDataSourceConnectionProviderTest.java
deleted file mode 100644
index 0a0809696..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/ExternalDataSourceConnectionProviderTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-public class ExternalDataSourceConnectionProviderTest {
-
- /*protected Properties getProperties() {
- Properties properties = new Properties();
- properties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
- //log settings
- properties.put("hibernate.hbm2ddl.auto", "update");
- //data source settings
- properties.put("hibernate.connection.datasource", newDataSource());
- return properties;
- }
-
- @Override
- protected SessionFactory newSessionFactory() {
- Properties properties = getProperties();
-
- return new Configuration()
- .addProperties(properties)
- .addAnnotatedClass(SecurityId.class)
- .buildSessionFactory(
- new StandardServiceRegistryBuilder()
- .applySettings(properties)
- .build()
- );
- }
-
- protected ProxyDataSource newDataSource() {
- JDBCDataSource actualDataSource = new JDBCDataSource();
- actualDataSource.setUrl("jdbc:hsqldb:mem:test");
- actualDataSource.setUser("sa");
- actualDataSource.setPassword("");
- ProxyDataSource proxyDataSource = new ProxyDataSource();
- proxyDataSource.setDataSource(actualDataSource);
- proxyDataSource.setListener(new SLF4JQueryLoggingListener());
- return proxyDataSource;
- }*/
-
-
-
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/FlexyPoolHibernateConnectionProvider.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/FlexyPoolHibernateConnectionProvider.java
deleted file mode 100644
index 598d55721..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/FlexyPoolHibernateConnectionProvider.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import com.vladmihalcea.flexypool.FlexyPoolDataSource;
-import org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl;
-
-import javax.sql.DataSource;
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.util.Map;
-
-/**
- * @author Vlad Mihalcea
- */
-public class FlexyPoolHibernateConnectionProvider
- extends DatasourceConnectionProviderImpl {
-
- private transient FlexyPoolDataSource flexyPoolDataSource;
-
- @Override
- public void configure(Map props) {
- super.configure(props);
- flexyPoolDataSource = new FlexyPoolDataSource<>(getDataSource());
- }
-
- @Override
- public Connection getConnection() throws SQLException {
- return flexyPoolDataSource.getConnection();
- }
-
- @Override
- public boolean isUnwrappableAs(Class unwrapType) {
- return super.isUnwrappableAs(unwrapType) ||
- getClass().isAssignableFrom(unwrapType);
- }
-
- @Override public void stop() {
- flexyPoolDataSource.stop();
- super.stop();
- }
-}
\ No newline at end of file
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/FlexyPoolTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/FlexyPoolTest.java
deleted file mode 100644
index 7867c352c..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/FlexyPoolTest.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import com.vladmihalcea.book.hpjp.hibernate.connection.jta.FlexyPoolEntities;
-import com.vladmihalcea.flexypool.FlexyPoolDataSource;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.transaction.support.TransactionCallback;
-import org.springframework.transaction.support.TransactionTemplate;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.sql.DataSource;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.*;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = FlexyPoolTestConfiguration.class)
-@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
-public class FlexyPoolTest {
-
- protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
-
- @PersistenceContext
- private EntityManager entityManager;
-
- @Autowired
- private TransactionTemplate transactionTemplate;
-
- @Autowired
- private DataSource dataSource;
-
- private int threadCount = 1;
- private int seconds = 60;
-
- private ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
-
- @Before
- public void init() {
- FlexyPoolDataSource flexyPoolDataSource = (FlexyPoolDataSource) dataSource;
- flexyPoolDataSource.start();
- }
-
- @After
- public void destroy() {
- FlexyPoolDataSource flexyPoolDataSource = (FlexyPoolDataSource) dataSource;
- flexyPoolDataSource.stop();
- }
-
- @Test
- public void test() throws InterruptedException, ExecutionException {
- long startNanos = System.nanoTime();
- while (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startNanos) < seconds){
- List> futures = new ArrayList<>();
- for (int i = 0; i < threadCount; i++) {
- futures.add(executorService.submit((Callable) () -> {
- transactionTemplate.execute((TransactionCallback) transactionStatus -> {
- for (int j = 0; j < 1000; j++) {
- entityManager.persist(new FlexyPoolEntities.Post());
- }
- entityManager.createQuery("select count(p) from Post p").getSingleResult();
- return null;
- });
- return null;
- }));
- }
- for (Future future : futures) {
- future.get();
- }
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/FlexyPoolTestConfiguration.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/FlexyPoolTestConfiguration.java
deleted file mode 100644
index 9580bb02c..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/FlexyPoolTestConfiguration.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import com.vladmihalcea.book.hpjp.hibernate.connection.jta.FlexyPoolEntities;
-import com.vladmihalcea.book.hpjp.util.spring.config.jpa.PostgreSQLJpaConfiguration;
-import com.vladmihalcea.flexypool.FlexyPoolDataSource;
-import com.vladmihalcea.flexypool.adaptor.DataSourcePoolAdapter;
-import org.springframework.context.annotation.Configuration;
-
-import javax.sql.DataSource;
-
-@Configuration
-public class FlexyPoolTestConfiguration extends PostgreSQLJpaConfiguration {
-
- @Override
- protected Class configurationClass() {
- return FlexyPoolEntities.class;
- }
-
- @Override
- public DataSource actualDataSource() {
- final DataSource dataSource = super.actualDataSource();
- com.vladmihalcea.flexypool.config.Configuration configuration = new com.vladmihalcea.flexypool.config.Configuration.Builder<>(
- getClass().getSimpleName(), dataSource, DataSourcePoolAdapter.FACTORY).build();
- FlexyPoolDataSource flexyPoolDataSource = new FlexyPoolDataSource<>(configuration);
- return flexyPoolDataSource;
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/HikariCPCockroachDBConnectionProviderTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/HikariCPCockroachDBConnectionProviderTest.java
deleted file mode 100644
index a6d4f25cb..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/HikariCPCockroachDBConnectionProviderTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.atomic.AtomicLong;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.ManyToMany;
-import javax.persistence.OneToMany;
-import javax.persistence.OneToOne;
-import javax.persistence.Table;
-import javax.persistence.Version;
-
-import org.hibernate.hikaricp.internal.HikariCPConnectionProvider;
-
-import org.junit.Test;
-
-import com.vladmihalcea.book.hpjp.util.providers.CockroachDBDataSourceProvider;
-import com.vladmihalcea.book.hpjp.util.providers.DataSourceProvider;
-import com.vladmihalcea.book.hpjp.util.providers.HsqldbDataSourceProvider;
-import com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider;
-
-public class HikariCPCockroachDBConnectionProviderTest extends DriverConnectionProviderTest {
-
- @Override
- protected Class>[] entities() {
- return new Class[] {
- Post.class
- };
- }
-
- protected DataSourceProvider dataSourceProvider() {
- return new CockroachDBDataSourceProvider();
- }
-
- @Override
- protected void appendDriverProperties(Properties properties) {
- DataSourceProvider dataSourceProvider = dataSourceProvider();
- properties.put("hibernate.connection.provider_class", HikariCPConnectionProvider.class.getName());
- properties.put("hibernate.hikari.minimumPoolSize", "1");
- properties.put("hibernate.hikari.maximumPoolSize", "2");
- properties.put("hibernate.hikari.transactionIsolation", "TRANSACTION_SERIALIZABLE");
- properties.put("hibernate.hikari.dataSourceClassName", dataSourceProvider.dataSourceClassName().getName());
- properties.put("hibernate.hikari.dataSource.url", dataSourceProvider.url());
- properties.put("hibernate.hikari.dataSource.user", dataSourceProvider.username());
- properties.put("hibernate.hikari.dataSource.password", dataSourceProvider.password());
- }
-
- @Test
- public void testConnection() {
- for (final AtomicLong i = new AtomicLong(); i.get() < 5; i.incrementAndGet()) {
- doInJPA(em -> {
- em.persist(new Post(i.get()));
- });
- }
-
- doInJPA(em -> {
- Post post = em.find(Post.class, 1L);
- });
- doInJPA(em -> {
- em.createQuery("select p from Post p", Post.class).getResultList();
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- 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;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/HikariCPConnectionProviderTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/HikariCPConnectionProviderTest.java
deleted file mode 100644
index 16f19e626..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/HikariCPConnectionProviderTest.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import org.hibernate.hikaricp.internal.HikariCPConnectionProvider;
-
-import java.util.Properties;
-
-import com.vladmihalcea.book.hpjp.util.providers.DataSourceProvider;
-
-public class HikariCPConnectionProviderTest extends DriverConnectionProviderTest {
-
- @Override
- protected void appendDriverProperties(Properties properties) {
- DataSourceProvider dataSourceProvider = dataSourceProvider();
- properties.put("hibernate.connection.provider_class", HikariCPConnectionProvider.class.getName());
- properties.put("hibernate.hikari.maximumPoolSize", "5");
- properties.put("hibernate.hikari.dataSourceClassName", dataSourceProvider.dataSourceClassName().getName());
- properties.put("hibernate.hikari.dataSource.url", dataSourceProvider.url());
- properties.put("hibernate.hikari.dataSource.user", dataSourceProvider.username());
- properties.put("hibernate.hikari.dataSource.password", dataSourceProvider.password());
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/JPADataSourceConnectionProviderTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/JPADataSourceConnectionProviderTest.java
deleted file mode 100644
index e974585a7..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/JPADataSourceConnectionProviderTest.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import com.vladmihalcea.book.hpjp.util.PersistenceUnitInfoImpl;
-
-import java.util.Properties;
-
-public class JPADataSourceConnectionProviderTest extends DriverConnectionProviderTest {
-
- protected void appendDriverProperties(Properties properties) {
-
- }
-
- @Override
- protected PersistenceUnitInfoImpl persistenceUnitInfo(String name) {
- PersistenceUnitInfoImpl persistenceUnitInfo = super.persistenceUnitInfo(name);
- return persistenceUnitInfo.setNonJtaDataSource(dataSourceProvider().dataSource());
- }
-
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/JPADriverConnectionProviderTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/JPADriverConnectionProviderTest.java
deleted file mode 100644
index 09fbc29e4..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/JPADriverConnectionProviderTest.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import java.util.Properties;
-
-import com.vladmihalcea.book.hpjp.util.providers.DataSourceProvider;
-
-public class JPADriverConnectionProviderTest extends DriverConnectionProviderTest {
-
- protected void appendDriverProperties(Properties properties) {
- DataSourceProvider dataSourceProvider = dataSourceProvider();
- properties.put("javax.persistence.jdbc.driver", "org.hsqldb.jdbcDriver");
- properties.put("javax.persistence.jdbc.url", dataSourceProvider.url());
- properties.put("javax.persistence.jdbc.user", dataSourceProvider.username());
- properties.put("javax.persistence.jdbc.password", dataSourceProvider.password());
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/ResourceLocalDelayConnectionAcquisitionTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/ResourceLocalDelayConnectionAcquisitionTest.java
deleted file mode 100644
index 225e1a2f1..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/ResourceLocalDelayConnectionAcquisitionTest.java
+++ /dev/null
@@ -1,267 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection;
-
-import java.io.InputStream;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
-import javax.sql.DataSource;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.junit.Test;
-
-import com.codahale.metrics.MetricRegistry;
-import com.codahale.metrics.Slf4jReporter;
-import com.codahale.metrics.Timer;
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import com.vladmihalcea.flexypool.FlexyPoolDataSource;
-import com.vladmihalcea.flexypool.adaptor.DataSourcePoolAdapter;
-import com.zaxxer.hikari.HikariConfig;
-import com.zaxxer.hikari.HikariDataSource;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-public class ResourceLocalDelayConnectionAcquisitionTest extends AbstractTest {
-
- public static final String DATA_FILE_PATH = "data/weather.xml";
-
- private SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
-
- private long warmUpDuration = TimeUnit.SECONDS.toNanos( 10 );
-
- private long measurementsDuration = TimeUnit.SECONDS.toNanos( 17 );
-
- private int parseCount = 100;
-
- private FlexyPoolDataSource flexyPoolDataSource;
-
- private MetricRegistry metricRegistry = new MetricRegistry();
-
- private Timer timer = metricRegistry.timer( getClass().getSimpleName() );
-
- private Slf4jReporter logReporter = Slf4jReporter
- .forRegistry(metricRegistry)
- .outputTo(LOGGER)
- .build();
-
- @Override
- protected Class>[] entities() {
- return new Class[] {
- Forecast.class
- };
- }
-
- protected boolean connectionPooling() {
- return false;
- }
-
- protected HikariConfig hikariConfig(DataSource dataSource) {
- HikariConfig hikariConfig = super.hikariConfig( dataSource );
- hikariConfig.setAutoCommit( false );
- return hikariConfig;
- }
-
- protected HikariDataSource connectionPoolDataSource(DataSource dataSource) {
- HikariConfig hikariConfig = new HikariConfig();
- int cpuCores = Runtime.getRuntime().availableProcessors();
- hikariConfig.setMaximumPoolSize(cpuCores * 4);
- hikariConfig.setDataSource(dataSource);
-
- return new HikariDataSource(hikariConfig);
- }
-
- @Override
- protected DataSource newDataSource() {
- DataSource dataSource = super.newDataSource();
-
- com.vladmihalcea.flexypool.config.Configuration configuration = new com.vladmihalcea.flexypool.config.Configuration.Builder<>(
- getClass().getSimpleName(), dataSource, DataSourcePoolAdapter.FACTORY)
- .setMetricLogReporterMillis( TimeUnit.SECONDS.toMillis( 15 ) )
- .build();
- flexyPoolDataSource = new FlexyPoolDataSource<>( configuration);
- return flexyPoolDataSource;
- }
-
- protected Properties properties() {
- Properties properties = super.properties();
- properties.put("hibernate.jdbc.batch_size", "50");
- properties.put("hibernate.connection.provider_disables_autocommit", "true");
- return properties;
- }
-
- @Test
- public void testConnection() {
- long warmUpThreshold = System.nanoTime() + warmUpDuration;
- LOGGER.info( "Warming up" );
-
- while ( System.nanoTime() < warmUpThreshold ) {
- importForecasts();
- }
-
- long measurementsThreshold = System.nanoTime() + measurementsDuration;
-
- LOGGER.info( "Measuring" );
- flexyPoolDataSource.start();
- int transactionCount = 0;
- while ( System.nanoTime() < measurementsThreshold ) {
- importForecasts();
- transactionCount++;
- }
- flexyPoolDataSource.stop();
- logReporter.report();
- LOGGER.info( "Transaction throughput: {}", transactionCount);
- }
-
- private void importForecasts() {
- doInJPA(entityManager -> {
- long startNanos = System.nanoTime();
- List forecasts = null;
- for ( int i = 0; i < parseCount; i++ ) {
- Document forecastXmlDocument = readXmlDocument( DATA_FILE_PATH );
- forecasts = parseForecasts(forecastXmlDocument);
- }
- timer.update( System.nanoTime() - startNanos, TimeUnit.NANOSECONDS );
-
- if ( forecasts != null ) {
- for(Forecast forecast : forecasts.subList( 0, 50 )) {
- entityManager.persist( forecast );
- }
- }
- });
- }
-
- private Document readXmlDocument(String filePath) {
- try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( filePath )) {
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- Document doc = dBuilder.parse( inputStream );
-
- doc.getDocumentElement().normalize();
-
- return doc;
- }
- catch (Exception e) {
- throw new IllegalArgumentException( e );
- }
- }
-
- private List parseForecasts(Document xmlDocument) {
- NodeList cityNodes = xmlDocument.getElementsByTagName( "localitate");
- List forecasts = new ArrayList<>( );
- for ( int i = 0; i < cityNodes.getLength(); i++ ) {
- Node cityNode = cityNodes.item(i);
- String city = cityNode.getAttributes().getNamedItem( "nume" ).getNodeValue();
-
- NodeList forecastNodes = cityNode.getChildNodes();
- for ( int j = 0; j < forecastNodes.getLength(); j++ ) {
- Node forecastNode = forecastNodes.item(j);
- if( !"prognoza".equals( forecastNode.getNodeName() ) ) {
- continue;
- }
-
- Forecast forecast = new Forecast();
- forecast.setCity( city );
-
- String dateValue = forecastNode.getAttributes().getNamedItem( "data" ).getNodeValue();
- try {
- forecast.setDate( simpleDateFormat.parse( dateValue ) );
- }
- catch (ParseException e) {
- throw new IllegalArgumentException( e );
- }
-
- NodeList forecastDetailsNodes = forecastNode.getChildNodes();
- for ( int k = 0; k < forecastDetailsNodes.getLength(); k++ ) {
- Node forecastDetailsNode = forecastDetailsNodes.item(k);
- switch ( forecastDetailsNode.getNodeName() ) {
- case "temp_min":
- forecast.setTemperatureMin( Byte.valueOf( forecastDetailsNode.getTextContent() ) );
- break;
- case "temp_max":
- forecast.setTemperatureMax( Byte.valueOf( forecastDetailsNode.getTextContent() ) );
- break;
- case "fenomen_descriere":
- forecast.setDescription( forecastDetailsNode.getTextContent() );
- break;
- }
- }
-
- forecasts.add( forecast );
- }
- }
- return forecasts;
- }
-
- @Entity(name = "Forecast")
- public static class Forecast {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String city;
-
- @Temporal( TemporalType.DATE )
- @Column(name = "forecast_date")
- private Date date;
-
- @Column(name = "temperature_min")
- private byte temperatureMin;
-
- @Column(name = "temperature_max")
- private byte temperatureMax;
-
- private String description;
-
- public String getCity() {
- return city;
- }
-
- public void setCity(String city) {
- this.city = city;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setDate(Date date) {
- this.date = date;
- }
-
- public byte getTemperatureMin() {
- return temperatureMin;
- }
-
- public void setTemperatureMin(byte temperatureMin) {
- this.temperatureMin = temperatureMin;
- }
-
- public byte getTemperatureMax() {
- return temperatureMax;
- }
-
- public void setTemperatureMax(byte temperatureMax) {
- this.temperatureMax = temperatureMax;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaConnectionReleaseConfiguration.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaConnectionReleaseConfiguration.java
deleted file mode 100644
index 73880c033..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaConnectionReleaseConfiguration.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection.jta;
-
-import com.vladmihalcea.book.hpjp.hibernate.statistics.TransactionStatisticsFactory;
-import com.vladmihalcea.book.hpjp.util.spring.config.jta.PostgreSQLJtaTransactionManagerConfiguration;
-import org.springframework.context.annotation.Configuration;
-
-import java.util.Properties;
-
-@Configuration
-public class JtaConnectionReleaseConfiguration extends PostgreSQLJtaTransactionManagerConfiguration {
-
- @Override
- protected Class configurationClass() {
- return this.getClass();
- }
-
- @Override
- protected Properties additionalProperties() {
- Properties properties = super.additionalProperties();
- properties.put("hibernate.generate_statistics", "true");
- properties.put("hibernate.stats.factory", TransactionStatisticsFactory.class.getName());
-
- //properties.setProperty("hibernate.connection.release_mode", "after_transaction");
- properties.setProperty("hibernate.connection.release_mode", "after_statement");
- return properties;
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaConnectionReleaseTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaConnectionReleaseTest.java
deleted file mode 100644
index 74bebcef4..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaConnectionReleaseTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection.jta;
-
-import org.hibernate.Session;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.transaction.support.TransactionCallback;
-import org.springframework.transaction.support.TransactionTemplate;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import java.util.concurrent.TimeUnit;
-
-import static org.junit.Assert.assertNotNull;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = JtaConnectionReleaseConfiguration.class)
-@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
-public class JtaConnectionReleaseTest {
-
- protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
-
- @PersistenceContext
- private EntityManager entityManager;
-
- @Autowired
- private TransactionTemplate transactionTemplate;
-
- private int[] batches = {10, 50, 100, 500, 1000, 5000, 10000};
-
- @Test
- public void test() {
- //Warming up
- for (int i = 0; i < 100; i++) {
- transactionTemplate.execute((TransactionCallback) transactionStatus -> {
- assertNotNull(entityManager.createNativeQuery("select now()").getSingleResult());
- return null;
- });
- }
- for (int batch : batches) {
- long startNanos = System.nanoTime();
- transactionTemplate.execute((TransactionCallback) transactionStatus -> {
- for (int i = 0; i < batch; i++) {
- assertNotNull(entityManager.createNativeQuery("select now()").getSingleResult());
- }
- return null;
- });
- LOGGER.info("Transaction took {} millis", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos));
- }
- transactionTemplate.execute((TransactionCallback) transactionStatus -> {
- entityManager.unwrap(Session.class).getSessionFactory().getStatistics().logSummary();
- return null;
- });
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaFlexyPoolTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaFlexyPoolTest.java
deleted file mode 100644
index 1a06a5032..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaFlexyPoolTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection.jta;
-
-import com.vladmihalcea.flexypool.FlexyPoolDataSource;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.transaction.support.TransactionCallback;
-import org.springframework.transaction.support.TransactionTemplate;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.sql.DataSource;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.*;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = JtaFlexyPoolTestConfiguration.class)
-@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
-public class JtaFlexyPoolTest {
-
- protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
-
- @PersistenceContext
- private EntityManager entityManager;
-
- @Autowired
- private TransactionTemplate transactionTemplate;
-
- @Autowired
- private DataSource dataSource;
-
- private int threadCount = 10;
- private int seconds = 60;
-
- private ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
-
- @Before
- public void init() {
- FlexyPoolDataSource flexyPoolDataSource = (FlexyPoolDataSource) dataSource;
- flexyPoolDataSource.start();
- }
-
- @After
- public void destroy() {
- FlexyPoolDataSource flexyPoolDataSource = (FlexyPoolDataSource) dataSource;
- flexyPoolDataSource.stop();
- }
-
- @Test
- public void test() throws InterruptedException, ExecutionException {
- long startNanos = System.nanoTime();
- while (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startNanos) < seconds){
- List> futures = new ArrayList<>();
- for (int i = 0; i < threadCount; i++) {
- futures.add(executorService.submit((Callable) () -> {
- transactionTemplate.execute((TransactionCallback) transactionStatus -> {
- for (int j = 0; j < 1000; j++) {
- entityManager.persist(new FlexyPoolEntities.Post());
- }
- entityManager.createQuery("select count(p) from Post p").getSingleResult();
- return null;
- });
- return null;
- }));
- }
- for (Future future : futures) {
- future.get();
- }
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaFlexyPoolTestConfiguration.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaFlexyPoolTestConfiguration.java
deleted file mode 100644
index ce15fa6fd..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/connection/jta/JtaFlexyPoolTestConfiguration.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.connection.jta;
-
-import bitronix.tm.resource.jdbc.PoolingDataSource;
-import com.vladmihalcea.book.hpjp.util.spring.config.jta.PostgreSQLJtaTransactionManagerConfiguration;
-import com.vladmihalcea.flexypool.FlexyPoolDataSource;
-import com.vladmihalcea.flexypool.adaptor.BitronixPoolAdapter;
-import org.springframework.context.annotation.Configuration;
-
-import javax.sql.DataSource;
-
-@Configuration
-public class JtaFlexyPoolTestConfiguration extends PostgreSQLJtaTransactionManagerConfiguration {
-
- @Override
- protected Class configurationClass() {
- return FlexyPoolEntities.class;
- }
-
- @Override
- public DataSource actualDataSource() {
- final PoolingDataSource poolingDataSource = (PoolingDataSource) super.actualDataSource();
- com.vladmihalcea.flexypool.config.Configuration configuration = new com.vladmihalcea.flexypool.config.Configuration.Builder<>(
- getClass().getSimpleName(), poolingDataSource, BitronixPoolAdapter.FACTORY).build();
-
- FlexyPoolDataSource flexyPoolDataSource = new FlexyPoolDataSource(configuration) {
- @Override
- public void start() {
- poolingDataSource.init();
- super.start();
- }
-
- @Override
- public void stop() {
- super.stop();
- poolingDataSource.close();
- }
- };
- return flexyPoolDataSource;
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/criteria/CriteriaFetchAliasTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/criteria/CriteriaFetchAliasTest.java
deleted file mode 100644
index 6d9c4cfb1..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/criteria/CriteriaFetchAliasTest.java
+++ /dev/null
@@ -1,209 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.criteria;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.Criteria;
-import org.hibernate.FetchMode;
-import org.hibernate.Session;
-import org.hibernate.criterion.Restrictions;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Vlad Mihalcea
- */
-public class CriteriaFetchAliasTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void test() {
- doInJPA(entityManager -> {
- Post post = new Post(1L);
- post.title = "Postit";
-
- PostComment comment1 = new PostComment();
- comment1.id = 1L;
- comment1.review = "Good";
-
- PostComment comment2 = new PostComment();
- comment2.id = 2L;
- comment2.review = "Excellent";
-
- post.addComment(comment1);
- post.addComment(comment2);
- entityManager.persist(post);
-
- Session session = entityManager.unwrap(Session.class);
- Criteria criteria = session.createCriteria(Post.class)
- .add(Restrictions.eq("title", "post"));
-
- LOGGER.info("Criteria: {}", criteria);
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("No alias");
- Session session = entityManager.unwrap(Session.class);
- List posts = session
- .createCriteria(Post.class)
- .setFetchMode("comments", FetchMode.JOIN)
- .add(Restrictions.eq("title", "Postit"))
- .list();
- assertEquals(2, posts.size());
- });
-
- try {
- doInJPA(entityManager -> {
- LOGGER.info("With alias");
- Session session = entityManager.unwrap(Session.class);
- List posts = session
- .createCriteria(Post.class, "post")
- .setFetchMode("post.comments", FetchMode.JOIN)
- .add(Restrictions.eq("post.title", "Postit"))
- .list();
- assertEquals(2, posts.size());
- });
- } catch (Throwable e) {
- LOGGER.error("Failure", e);
- }
-
- doInJPA(entityManager -> {
- Post newPost = new Post(2L);
- entityManager.persist(newPost);
- });
- doInJPA(entityManager -> {
- LOGGER.info("In query");
- Session session = entityManager.unwrap(Session.class);
-
-
- List postComments = new ArrayList<>();
- postComments.add(new PostComment());
- postComments.get(0).setId(2L);
- postComments.add(new PostComment());
- postComments.get(1).setId(3L);
-
-
- List ids = postComments.stream().map(PostComment::getId).collect(Collectors.toList());
- List filtered = session.createCriteria(Post.class)
- .createAlias("comments", "c")
- .add( Restrictions.in( "c.id", ids ) )
- .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
- .list();
- assertEquals(1, filtered.size());
-
- ids = new ArrayList<>();
- ids.add(3L);
- ids.add(4L);
-
- filtered = session.createCriteria(Post.class)
- .createAlias("comments", "c")
- .add( Restrictions.in( "c.id", ids ) )
- .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
- .list();
- assertEquals(0, filtered.size());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne
- private Post post;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/criteria/CriteriaNestedQueryTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/criteria/CriteriaNestedQueryTest.java
deleted file mode 100644
index c7a3b679e..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/criteria/CriteriaNestedQueryTest.java
+++ /dev/null
@@ -1,165 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.criteria;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.Criteria;
-import org.hibernate.Session;
-import org.hibernate.criterion.DetachedCriteria;
-import org.hibernate.criterion.Projections;
-import org.hibernate.criterion.Restrictions;
-import org.hibernate.criterion.Subqueries;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Vlad Mihalcea
- */
-public class CriteriaNestedQueryTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void test() {
- doInJPA(entityManager -> {
- Post post = new Post(1L);
- post.title = "Postit";
-
- PostComment comment1 = new PostComment();
- comment1.id = 1L;
- comment1.review = "Good";
-
- PostComment comment2 = new PostComment();
- comment2.id = 2L;
- comment2.review = "Excellent";
-
- post.addComment(comment1);
- post.addComment(comment2);
- entityManager.persist(post);
-
- Session session = entityManager.unwrap(Session.class);
- Criteria criteria = session.createCriteria(Post.class)
- .add(Restrictions.eq("title", "post"));
-
- LOGGER.info("Criteria: {}", criteria);
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("No alias");
- Session session = entityManager.unwrap(Session.class);
-
- DetachedCriteria innerCriteria = DetachedCriteria.forClass(PostComment.class, "inner")
- .add(Restrictions.eqProperty("inner.post.id","upper.id"))
- .setProjection(Projections.projectionList().add(Projections.max("inner.id")));
-
- DetachedCriteria outerCriteria= DetachedCriteria.forClass(Post.class, "upper");
- outerCriteria.createAlias("upper.comments", "comments");
- outerCriteria.add(Subqueries.propertyEq("comments.id", innerCriteria ));
- outerCriteria.add(Restrictions.eq("comments.review", "Excellent"));
-
- List posts = outerCriteria.getExecutableCriteria(session).list();
- assertEquals(1, posts.size());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- public Post() {}
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- 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 List getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/AbstractEqualityCheckTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/AbstractEqualityCheckTest.java
deleted file mode 100644
index 951e76447..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/AbstractEqualityCheckTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.equality;
-
-import com.vladmihalcea.book.hpjp.hibernate.identifier.Identifiable;
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.Session;
-
-import java.io.Serializable;
-import java.util.HashSet;
-import java.util.Set;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author Vlad Mihalcea
- */
-public abstract class AbstractEqualityCheckTest extends AbstractTest {
-
- protected > void assertEqualityConstraints(Class clazz, T entity) {
- Set tuples = new HashSet<>();
-
- assertFalse(tuples.contains(entity));
- tuples.add(entity);
- assertTrue(tuples.contains(entity));
-
- doInJPA(entityManager -> {
- entityManager.persist(entity);
- entityManager.flush();
- assertTrue("The entity is found after it's persisted",
- tuples.contains(entity));
- });
-
- //The entity is found after the entity is detached
- assertTrue(tuples.contains(entity));
-
- doInJPA(entityManager -> {
- T _entity = entityManager.merge(entity);
- assertTrue("The entity is found after it's merged",
- tuples.contains(_entity));
- });
-
- doInJPA(entityManager -> {
- entityManager.unwrap(Session.class).update(entity);
- assertTrue("The entity is found after it's reattached",
- tuples.contains(entity));
- });
-
- doInJPA(entityManager -> {
- T _entity = entityManager.find(clazz, entity.getId());
- assertTrue("The entity is found after it's loaded " +
- "in an other Persistence Context",
- tuples.contains(_entity));
- });
-
- doInJPA(entityManager -> {
- T _entity = entityManager.getReference(clazz, entity.getId());
- assertTrue("The entity is found after it's loaded as a Proxy " +
- "in an other Persistence Context",
- tuples.contains(_entity));
- });
-
- executeSync(() -> {
- doInJPA(entityManager -> {
- T _entity = entityManager.find(clazz, entity.getId());
- assertTrue("The entity is found after it's loaded " +
- "in an other Persistence Context and " +
- "in an other thread",
- tuples.contains(_entity));
- });
- });
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/DefaultEqualityTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/DefaultEqualityTest.java
deleted file mode 100644
index 664847301..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/DefaultEqualityTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.equality;
-
-import com.vladmihalcea.book.hpjp.hibernate.identifier.Identifiable;
-import org.junit.Test;
-
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-/**
- * @author Vlad Mihalcea
- */
-public class DefaultEqualityTest extends AbstractEqualityCheckTest {
-
- @Override
- protected Class>[] entities() {
- return new Class[]{
- Post.class
- };
- }
-
- @Test
- public void testEquality() {
- Post post = new Post();
- post.setTitle("High-PerformanceJava Persistence");
-
- assertEqualityConstraints(Post.class, post);
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post implements Identifiable {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- 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;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/DefaultIdEqualityTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/DefaultIdEqualityTest.java
deleted file mode 100644
index f231763ac..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/DefaultIdEqualityTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.equality;
-
-import com.vladmihalcea.book.hpjp.hibernate.identifier.Identifiable;
-import org.junit.Test;
-
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.Table;
-import java.util.Objects;
-
-/**
- * @author Vlad Mihalcea
- */
-public class DefaultIdEqualityTest extends AbstractEqualityCheckTest {
-
- @Override
- protected Class>[] entities() {
- return new Class[] {
- Post.class
- };
- }
-
- @Test
- public void testEquality() {
- Post post = new Post();
- post.setTitle("High-PerformanceJava Persistence");
-
- assertEqualityConstraints(Post.class, post);
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post implements Identifiable {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof Post)) return false;
- return Objects.equals(id, ((Post) o).id);
- }
- @Override
- public int hashCode() {
- return Objects.hash(id);
- }
-
- 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;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/ProperIdEqualityTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/ProperIdEqualityTest.java
deleted file mode 100644
index 9c71f9311..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/equality/ProperIdEqualityTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.equality;
-
-import com.vladmihalcea.book.hpjp.hibernate.identifier.Identifiable;
-import org.junit.Test;
-
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-/**
- * @author Vlad Mihalcea
- */
-public class ProperIdEqualityTest extends AbstractEqualityCheckTest {
-
- @Override
- protected Class>[] entities() {
- return new Class[] {
- Post.class
- };
- }
-
- @Test
- public void testEquality() {
- Post post = new Post();
- post.setTitle("High-PerformanceJava Persistence");
-
- assertEqualityConstraints(Post.class, post);
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post implements Identifiable {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- public Post() {}
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof Post)) return false;
- return id != null && id.equals(((Post) o).id);
- }
-
- @Override
- public int hashCode() {
- return 31;
- }
-
- 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;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/CriteriaAPITest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/CriteriaAPITest.java
deleted file mode 100644
index 84f6529c7..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/CriteriaAPITest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.hibernate.forum.*;
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.junit.Test;
-
-import javax.persistence.EntityManager;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Predicate;
-import javax.persistence.criteria.Root;
-import java.util.List;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author Vlad Mihalcea
- */
-public class CriteriaAPITest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class[] {
- Post.class,
- PostComment.class,
- Tag.class,
- PostDetails.class
- };
- }
-
-
- @Override
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("high-performance-java-persistence");
- entityManager.persist(post);
- });
- }
-
- @Test
- public void testFind() {
- doInJPA(entityManager -> {
- List posts = filterPosts(entityManager, "high-performance%");
- assertFalse(posts.isEmpty());
- });
- doInJPA(entityManager -> {
- List posts = filterPosts(entityManager, null);
- assertTrue(posts.isEmpty());
- });
- }
-
- private List filterPosts(EntityManager entityManager, String titlePattern) {
- CriteriaBuilder builder = entityManager.getCriteriaBuilder();
- CriteriaQuery criteria = builder.createQuery(Post.class);
- Root fromPost = criteria.from(Post.class);
-
- Predicate titlePredicate = titlePattern == null ?
- builder.isNull(fromPost.get(Post_.title)) :
- builder.like(fromPost.get(Post_.title), titlePattern);
-
- criteria.where(titlePredicate);
- List posts = entityManager.createQuery(criteria).getResultList();
-
- return posts;
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/DistinctTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/DistinctTest.java
deleted file mode 100644
index e186174db..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/DistinctTest.java
+++ /dev/null
@@ -1,184 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.hibernate.jpa.QueryHints;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Vlad Mihalcea
- */
-public class DistinctTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- };
- }
-
-
- @Override
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("High-Performance Java Persistence");
-
- post.addComment(new PostComment("Excellent!"));
- post.addComment(new PostComment("Great!"));
-
- entityManager.persist(post);
- });
- }
-
- @Test
- public void testWithoutDistinct() {
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "left join fetch p.comments " +
- "where p.title = :title", Post.class)
- .setParameter("title", "High-Performance Java Persistence")
- .getResultList();
-
- LOGGER.info("Fetched {} post entities: {}", posts.size(), posts);
- });
- }
-
- @Test
- public void testWithDistinctScalarQuery() {
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select distinct p.title " +
- "from Post p ", String.class)
- .getResultList();
-
- LOGGER.info("Fetched {} post entities: {}", posts.size(), posts);
- });
- }
-
- @Test
- public void testWithDistinct() {
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select distinct p " +
- "from Post p " +
- "left join fetch p.comments " +
- "where p.title = :title", Post.class)
- .setParameter("title", "High-Performance Java Persistence")
- .getResultList();
-
- LOGGER.info("Fetched {} post entities: {}", posts.size(), posts);
- });
- }
-
- @Test
- public void testWithDistinctAndQueryHint() {
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select distinct p " +
- "from Post p " +
- "left join fetch p.comments " +
- "where p.title = :title", Post.class)
- .setParameter("title", "High-Performance Java Persistence")
- .setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
- .getResultList();
-
- LOGGER.info("Fetched {} post entities: {}", posts.size(), posts);
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "post",
- orphanRemoval = true)
- private List comments = new ArrayList<>();
-
- 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 void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
-
- @Override
- public String toString() {
- return "Post{" +
- "id=" + id +
- ", title='" + title + '\'' +
- '}';
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public PostComment() {}
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/EagerFetchingManyToOneFindEntityTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/EagerFetchingManyToOneFindEntityTest.java
deleted file mode 100644
index 4f0d0de9f..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/EagerFetchingManyToOneFindEntityTest.java
+++ /dev/null
@@ -1,197 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.hibernate.logging.validator.sql.SQLStatementCountValidator;
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.Collections;
-import java.util.List;
-
-import static org.junit.Assert.assertNotNull;
-
-/**
- * @author Vlad Mihalcea
- */
-public class EagerFetchingManyToOneFindEntityTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- };
- }
-
-
- @Override
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle(String.format("Post nr. %d", 1));
- PostComment comment = new PostComment();
- comment.setId(1L);
- comment.setPost(post);
- comment.setReview("Excellent!");
- entityManager.persist(post);
- entityManager.persist(comment);
- });
- }
-
- @Test
- public void testFind() {
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L);
- assertNotNull(comment);
- });
- }
-
- @Test
- public void testFindWithQuery() {
- doInJPA(entityManager -> {
- Long commentId = 1L;
- PostComment comment = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "where pc.id = :id", PostComment.class)
- .setParameter("id", commentId)
- .getSingleResult();
- assertNotNull(comment);
- });
- }
-
- @Test
- public void testFindWithQueryAndFetch() {
- doInJPA(entityManager -> {
- Long commentId = 1L;
- PostComment comment = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "left join fetch pc.post p " +
- "where pc.id = :id", PostComment.class)
- .setParameter("id", commentId)
- .getSingleResult();
- assertNotNull(comment);
- });
- }
-
- @Test
- public void testFindWithNamedEntityGraph() {
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L,
- Collections.singletonMap(
- "javax.persistence.fetchgraph",
- entityManager.getEntityGraph("PostComment.post")
- )
- );
- LOGGER.info("Fetch entity graph");
- assertNotNull(comment);
- });
- }
-
- @Test
- public void testNPlusOneDetection() {
- try {
- String review = "Excellent!";
-
- doInJPA(entityManager -> {
- LOGGER.info("Detect N+1");
- SQLStatementCountValidator.reset();
- List comments = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "join fetch pc.post " +
- "where pc.review = :review", PostComment.class)
- .setParameter("review", review)
- .getResultList();
- SQLStatementCountValidator.assertSelectCount(1);
- });
- } catch (Exception expected) {
- LOGGER.error("Exception", expected);
- }
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- public Post() {
- }
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- 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;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- @NamedEntityGraph(name = "PostComment.post", attributeNodes = {})
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne
- private Post post;
-
- private String review;
-
- public PostComment() {
- }
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/EagerFetchingOneToManyBagsFindEntityTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/EagerFetchingOneToManyBagsFindEntityTest.java
deleted file mode 100644
index ec8fbeb68..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/EagerFetchingOneToManyBagsFindEntityTest.java
+++ /dev/null
@@ -1,177 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.junit.Assert.assertNotNull;
-
-/**
- * @author Vlad Mihalcea
- */
-public class EagerFetchingOneToManyBagsFindEntityTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- Tag.class
- };
- }
-
-
- @Override
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle(String.format("Post nr. %d", 1));
- PostComment comment = new PostComment();
- comment.setId(1L);
- comment.setReview("Excellent!");
- entityManager.persist(post);
- entityManager.persist(comment);
- post.comments.add(comment);
- });
- }
-
- @Test
- public void testGet() {
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertNotNull(post);
- });
- }
-
- @Test
- public void testFindWithQuery() {
- doInJPA(entityManager -> {
- Long postId = 1L;
- Post post = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "join fetch p.tags " +
- "join fetch p.comments " +
- "where p.id = :id", Post.class)
- .setParameter("id", postId)
- .getSingleResult();
- assertNotNull(post);
- });
- }
-
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @OneToMany(fetch = FetchType.EAGER)
- private List comments = new ArrayList<>();
-
- @ManyToMany(fetch = FetchType.EAGER)
- @JoinTable(name = "post_tag",
- joinColumns = @JoinColumn(name = "post_id"),
- inverseJoinColumns = @JoinColumn(name = "tag_id")
- )
- private List tags = new ArrayList<>();
-
- public Post() {
- }
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- 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 List getTags() {
- return tags;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- private Long id;
-
- private String review;
-
- public PostComment() {
- }
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-
- @Entity(name = "Tag")
- @Table(name = "tag")
- public static class Tag {
-
- @Id
- private Long id;
-
- private String name;
-
- 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;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/EagerFetchingOneToManyFindEntityTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/EagerFetchingOneToManyFindEntityTest.java
deleted file mode 100644
index 4c8fe6caa..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/EagerFetchingOneToManyFindEntityTest.java
+++ /dev/null
@@ -1,222 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-/**
- * @author Vlad Mihalcea
- */
-public class EagerFetchingOneToManyFindEntityTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- Tag.class
- };
- }
-
-
- @Override
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle(String.format("Post nr. %d", 1));
-
- for (long i = 0; i < 20; i++) {
- PostComment comment = new PostComment();
- comment.setId(i);
- post.addComment(comment);
- comment.setReview("Excellent!");
-
- entityManager.persist(comment);
- }
-
- for (long i = 0; i < 10; i++) {
- Tag tag = new Tag();
- tag.setId(i);
- tag.setName("My tag");
-
- entityManager.persist(tag);
- post.getTags().add(tag);
- }
-
- entityManager.persist(post);
- });
- }
-
- @Test
- public void testGet() {
- doInJPA(entityManager -> {
- Post post = entityManager.find(Post.class, 1L);
- assertNotNull(post);
- });
- }
-
- @Test
- public void testFindWithQuery() {
- doInJPA(entityManager -> {
- Long postId = 1L;
- Post post = entityManager.createQuery(
- "select p from Post p where p.id = :id", Post.class)
- .setParameter("id", postId)
- .getSingleResult();
- assertNotNull(post);
- });
- }
-
- @Test
- public void testFindWithJoinFetchQuery() {
- doInJPA(entityManager -> {
- Long postId = 1L;
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "left join fetch p.comments " +
- "left join fetch p.tags", Post.class)
- .getResultList();
- assertEquals(200, posts.size());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @OneToMany(mappedBy = "post", fetch = FetchType.EAGER)
- private Set comments = new HashSet<>();
-
- @ManyToMany(fetch = FetchType.EAGER)
- @JoinTable(name = "post_tag",
- joinColumns = @JoinColumn(name = "post_id"),
- inverseJoinColumns = @JoinColumn(name = "tag_id")
- )
- private Set tags = new HashSet<>();
-
- public Post() {
- }
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- 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 Set getComments() {
- return comments;
- }
-
- public void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
-
- public Set getTags() {
- return tags;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne
- private Post post;
-
- private String review;
-
- public PostComment() {
- }
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-
- @Entity(name = "Tag")
- @Table(name = "tag")
- public static class Tag {
-
- @Id
- private Long id;
-
- private String name;
-
- 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;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/HibernateProxyTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/HibernateProxyTest.java
deleted file mode 100644
index 18b90b413..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/HibernateProxyTest.java
+++ /dev/null
@@ -1,155 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import java.util.Objects;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.ManyToOne;
-import javax.persistence.Table;
-
-import org.hibernate.Hibernate;
-
-import org.junit.Test;
-
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-public class HibernateProxyTest extends AbstractTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void test() {
- Post _post = doInJPA(entityManager -> {
- Post post = new Post();
- post.setId( 1L );
- post.setTitle( "High-Performance Java Persistence" );
- entityManager.persist(post);
- return post;
- });
-
- doInJPA(entityManager -> {
- LOGGER.info( "Saving a PostComment" );
-
- Post post = entityManager.getReference(Post.class, 1L);
-
- PostComment comment = new PostComment();
- comment.setId( 1L );
- comment.setPost( post );
- comment.setReview( "A must read!" );
- entityManager.persist( comment );
- });
-
- doInJPA(entityManager -> {
- LOGGER.info( "Loading a PostComment" );
-
- PostComment comment = entityManager.find(
- PostComment.class,
- 1L
- );
-
- LOGGER.info( "Loading the Post Proxy" );
-
- assertEquals(
- "High-Performance Java Persistence",
- comment.getPost().getTitle()
- );
- });
-
- doInJPA(entityManager -> {
- LOGGER.info( "Equality check" );
- Post post = entityManager.getReference(Post.class, 1L);
- LOGGER.info( "Post entity class: {}", post.getClass().getName() );
-
- assertFalse(_post.equals(post));
-
- assertTrue(_post.equals( Hibernate.unproxy( post)));
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- 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;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof Post)) return false;
- return id != null && id.equals(((Post) o).id);
- }
-
- @Override
- public int hashCode() {
- return 31;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyAttributeTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyAttributeTest.java
deleted file mode 100644
index 03ae96157..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyAttributeTest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.hibernate.forum.Attachment;
-import com.vladmihalcea.book.hpjp.hibernate.forum.MediaType;
-import com.vladmihalcea.book.hpjp.util.AbstractMySQLIntegrationTest;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Properties;
-import java.util.concurrent.atomic.AtomicReference;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.fail;
-
-/**
- * @author Vlad Mihalcea
- */
-public class LazyAttributeTest extends AbstractMySQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[] {
- Attachment.class,
- };
- }
-
- @Override
- protected Properties properties() {
- Properties properties = super.properties();
- //properties.setProperty(AvailableSettings.USE_STREAMS_FOR_BINARY, Boolean.FALSE.toString());
- return properties;
- }
-
- @Test
- public void test() throws URISyntaxException {
- final Path bookFilePath = Paths.get(Thread.currentThread().getContextClassLoader().getResource("ehcache.xml").toURI());
- final Path videoFilePath = Paths.get(Thread.currentThread().getContextClassLoader().getResource("spy.properties").toURI());
-
- AtomicReference bookIdHolder = new AtomicReference<>();
- AtomicReference videoIdHolder = new AtomicReference<>();
-
- doInJPA(entityManager -> {
- try {
- Attachment book = new Attachment();
- book.setName("High-Performance Java Persistence");
- book.setMediaType(MediaType.PDF);
- book.setContent(Files.readAllBytes(bookFilePath));
- entityManager.persist(book);
-
- Attachment video = new Attachment();
- video.setName("High-Performance Hibernate");
- video.setMediaType(MediaType.MPEG_VIDEO);
- video.setContent(Files.readAllBytes(videoFilePath));
- entityManager.persist(video);
-
- bookIdHolder.set(book.getId());
- videoIdHolder.set(video.getId());
- } catch (IOException e) {
- fail(e.getMessage());
- }
- });
-
- doInJPA(entityManager -> {
- try {
- Long bookId = bookIdHolder.get();
- Long videoId = videoIdHolder.get();
-
- Attachment book = entityManager.find(Attachment.class, bookId);
- LOGGER.debug("Fetched book: {}", book.getName());
- assertArrayEquals(Files.readAllBytes(bookFilePath), book.getContent());
-
- Attachment video = entityManager.find(Attachment.class, videoId);
- LOGGER.debug("Fetched video: {}", video.getName());
- assertArrayEquals(Files.readAllBytes(videoFilePath), video.getContent());
- } catch (IOException e) {
- fail(e.getMessage());
- }
- });
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyFetchingManyToOneFindEntityTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyFetchingManyToOneFindEntityTest.java
deleted file mode 100644
index fe1989549..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyFetchingManyToOneFindEntityTest.java
+++ /dev/null
@@ -1,169 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.hibernate.forum.*;
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.hibernate.LazyInitializationException;
-import org.junit.Test;
-
-import javax.persistence.EntityGraph;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityTransaction;
-import java.util.Collections;
-import java.util.List;
-
-import static org.junit.Assert.assertNotNull;
-
-/**
- * @author Vlad Mihalcea
- */
-public class LazyFetchingManyToOneFindEntityTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- PostDetails.class,
- Tag.class
- };
- }
-
- @Test
- public void testFind() {
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle(String.format("Post nr. %d", 1));
- PostComment comment = new PostComment();
- comment.setId(1L);
- comment.setPost(post);
- comment.setReview("Excellent!");
- entityManager.persist(post);
- entityManager.persist(comment);
- });
-
- doInJPA(entityManager -> {
- PostComment comment = entityManager.find(PostComment.class, 1L);
- LOGGER.info("Loaded comment entity");
- LOGGER.info("The post title is '{}'", comment.getPost().getTitle());
- assertNotNull(comment);
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("Using custom entity graph");
-
- EntityGraph postEntityGraph = entityManager.createEntityGraph(
- PostComment.class);
- postEntityGraph.addAttributeNodes(PostComment_.post);
-
- PostComment comment = entityManager.find(PostComment.class, 1L,
- Collections.singletonMap("javax.persistence.fetchgraph", postEntityGraph)
- );
- LOGGER.info("Fetch entity graph");
- assertNotNull(comment);
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("Using JPQL");
-
- PostComment comment = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "join fetch pc.post p " +
- "where pc.id = :id", PostComment.class)
- .setParameter("id", 1L)
- .getSingleResult();
- assertNotNull(comment);
- });
- }
-
- @Test
- public void testNPlusOne() {
-
- String review = "Excellent!";
-
- doInJPA(entityManager -> {
-
- for (long i = 1; i < 4; i++) {
- Post post = new Post();
- post.setId(i);
- post.setTitle(String.format("Post nr. %d", i));
- entityManager.persist(post);
-
- PostComment comment = new PostComment();
- comment.setId(i);
- comment.setPost(post);
- comment.setReview(review);
- entityManager.persist(comment);
- }
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("N+1 query problem");
- List comments = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "where pc.review = :review", PostComment.class)
- .setParameter("review", review)
- .getResultList();
- LOGGER.info("Loaded {} comments", comments.size());
- for(PostComment comment : comments) {
- LOGGER.info("The post title is '{}'", comment.getPost().getTitle());
- }
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("N+1 query problem fixed");
- List comments = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "join fetch pc.post p " +
- "where pc.review = :review", PostComment.class)
- .setParameter("review", review)
- .getResultList();
- LOGGER.info("Loaded {} comments", comments.size());
- for(PostComment comment : comments) {
- LOGGER.info("The post title is '{}'", comment.getPost().getTitle());
- }
- });
- }
-
- @Test(expected = LazyInitializationException.class)
- public void testSessionIsClosed() {
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle(String.format("Post nr. %d", 1));
- PostComment comment = new PostComment();
- comment.setId(1L);
- comment.setPost(post);
- comment.setReview("Excellent!");
- entityManager.persist(post);
- entityManager.persist(comment);
- });
-
- PostComment comment = null;
-
- EntityManager entityManager = null;
- EntityTransaction transaction = null;
- try {
- entityManager = entityManagerFactory().createEntityManager();
- transaction = entityManager.getTransaction();
- transaction.begin();
-
- comment = entityManager.find(PostComment.class, 1L);
-
- transaction.commit();
- } catch (Throwable e) {
- if ( transaction != null && transaction.isActive())
- transaction.rollback();
- throw e;
- } finally {
- if (entityManager != null) {
- entityManager.close();
- }
- }
-
- LOGGER.info("The post title is '{}'", comment.getPost().getTitle());
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyFetchingOneToManyFindEntityTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyFetchingOneToManyFindEntityTest.java
deleted file mode 100644
index 29da275a0..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyFetchingOneToManyFindEntityTest.java
+++ /dev/null
@@ -1,152 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Vlad Mihalcea
- */
-public class LazyFetchingOneToManyFindEntityTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- };
- }
-
-
- @Override
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setId(1L);
- post.setTitle("high-performance-java-persistence");
- PostComment comment1 = new PostComment();
- comment1.setId(1L);
- comment1.setReview("Excellent!");
- PostComment comment2 = new PostComment();
- comment2.setId(2L);
- comment2.setReview("Good!");
- post.addComment(comment1);
- post.addComment(comment2);
- entityManager.persist(post);
- });
- }
-
- @Test
- public void testFetchAndPaginate() {
- doInJPA(entityManager -> {
- String titlePattern = "high-performance%";
- int maxResults = 5;
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "left join fetch p.comments " +
- "where p.title like :title " +
- "order by p.id", Post.class)
- .setParameter("title", titlePattern)
- .setMaxResults(maxResults)
- .getResultList();
- assertEquals(1, posts.size());
- assertEquals(2, posts.get(0).comments.size());
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- @OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
- private List comments = new ArrayList<>();
-
- public Post() {
- }
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- 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 void addComment(PostComment comment) {
- comments.add(comment);
- comment.setPost(this);
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne
- private Post post;
-
- private String review;
-
- public PostComment() {
- }
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyInitializationExceptionFixWithDTOTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyInitializationExceptionFixWithDTOTest.java
deleted file mode 100644
index ca4f69004..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyInitializationExceptionFixWithDTOTest.java
+++ /dev/null
@@ -1,143 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.List;
-
-/**
- * @author Vlad Mihalcea
- */
-public class LazyInitializationExceptionFixWithDTOTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void testNPlusOne() {
-
- String review = "Excellent!";
-
- doInJPA(entityManager -> {
-
- for (long i = 1; i < 4; i++) {
- Post post = new Post();
- post.setId(i);
- post.setTitle(String.format("Post nr. %d", i));
- entityManager.persist(post);
-
- PostComment comment = new PostComment();
- comment.setId(i);
- comment.setPost(post);
- comment.setReview(review);
- entityManager.persist(comment);
- }
- });
-
- List comments = doInJPA(entityManager -> {
- return entityManager.createQuery(
- "select new " +
- " com.vladmihalcea.book.hpjp.hibernate.fetching.PostCommentDTO(" +
- " pc.id, pc.review, p.title" +
- " ) " +
- "from PostComment pc " +
- "join pc.post p " +
- "where pc.review = :review", PostCommentDTO.class)
- .setParameter("review", review)
- .getResultList();
- });
-
- for(PostCommentDTO comment : comments) {
- LOGGER.info("The post title is '{}'", comment.getTitle());
- }
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- public Post() {
- }
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- 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;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- @NamedEntityGraph(name = "PostComment.post", attributeNodes = {})
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public PostComment() {
- }
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyInitializationExceptionTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyInitializationExceptionTest.java
deleted file mode 100644
index ed8126635..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/LazyInitializationExceptionTest.java
+++ /dev/null
@@ -1,162 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.hibernate.LazyInitializationException;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author Vlad Mihalcea
- */
-public class LazyInitializationExceptionTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class,
- };
- }
-
- @Test
- public void testNPlusOne() {
-
- String review = "Excellent!";
-
- doInJPA(entityManager -> {
-
- for (long i = 1; i < 4; i++) {
- Post post = new Post();
- post.setId(i);
- post.setTitle(String.format("Post nr. %d", i));
- entityManager.persist(post);
-
- PostComment comment = new PostComment();
- comment.setId(i);
- comment.setPost(post);
- comment.setReview(review);
- entityManager.persist(comment);
- }
- });
-
- List comments = null;
-
- EntityManager entityManager = null;
- EntityTransaction transaction = null;
- try {
- entityManager = entityManagerFactory().createEntityManager();
- transaction = entityManager.getTransaction();
- transaction.begin();
-
- comments = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "where pc.review = :review", PostComment.class)
- .setParameter("review", review)
- .getResultList();
-
- transaction.commit();
- } catch (Throwable e) {
- if ( transaction != null && transaction.isActive())
- transaction.rollback();
- throw e;
- } finally {
- if (entityManager != null) {
- entityManager.close();
- }
- }
- try {
- for(PostComment comment : comments) {
- LOGGER.info("The post title is '{}'", comment.getPost().getTitle());
- }
- } catch (LazyInitializationException expected) {
- assertEquals("could not initialize proxy - no Session", expected.getMessage());
- }
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- public Post() {
- }
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- 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;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- @NamedEntityGraph(name = "PostComment.post", attributeNodes = {})
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public PostComment() {
- }
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/NPlusOneLazyFetchingManyToOneFindEntityTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/NPlusOneLazyFetchingManyToOneFindEntityTest.java
deleted file mode 100644
index ec4eb6fd4..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/NPlusOneLazyFetchingManyToOneFindEntityTest.java
+++ /dev/null
@@ -1,154 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.List;
-
-/**
- * @author Vlad Mihalcea
- */
-public class NPlusOneLazyFetchingManyToOneFindEntityTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class,
- PostComment.class
- };
- }
-
- @Test
- public void testNPlusOne() {
-
- String review = "Excellent!";
-
- doInJPA(entityManager -> {
-
- for (long i = 1; i < 4; i++) {
- Post post = new Post();
- post.setId(i);
- post.setTitle(String.format("Post nr. %d", i));
- entityManager.persist(post);
-
- PostComment comment = new PostComment();
- comment.setId(i);
- comment.setPost(post);
- comment.setReview(review);
- entityManager.persist(comment);
- }
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("N+1 query problem");
- List comments = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "where pc.review = :review", PostComment.class)
- .setParameter("review", review)
- .getResultList();
- LOGGER.info("Loaded {} comments", comments.size());
- for(PostComment comment : comments) {
- LOGGER.info("The post title is '{}'", comment.getPost().getTitle());
- }
- });
-
- doInJPA(entityManager -> {
- LOGGER.info("N+1 query problem fixed");
- List comments = entityManager.createQuery(
- "select pc " +
- "from PostComment pc " +
- "join fetch pc.post p " +
- "where pc.review = :review", PostComment.class)
- .setParameter("review", review)
- .getResultList();
- LOGGER.info("Loaded {} comments", comments.size());
- for(PostComment comment : comments) {
- LOGGER.info("The post title is '{}'", comment.getPost().getTitle());
- }
- });
- }
-
- @Entity(name = "Post")
- @Table(name = "post")
- public static class Post {
-
- @Id
- private Long id;
-
- private String title;
-
- public Post() {
- }
-
- public Post(Long id) {
- this.id = id;
- }
-
- public Post(String title) {
- this.title = title;
- }
-
- 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;
- }
- }
-
- @Entity(name = "PostComment")
- @Table(name = "post_comment")
- @NamedEntityGraph(name = "PostComment.post", attributeNodes = {})
- public static class PostComment {
-
- @Id
- private Long id;
-
- @ManyToOne(fetch = FetchType.LAZY)
- private Post post;
-
- private String review;
-
- public PostComment() {
- }
-
- public PostComment(String review) {
- this.review = review;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Post getPost() {
- return post;
- }
-
- public void setPost(Post post) {
- this.post = post;
- }
-
- public String getReview() {
- return review;
- }
-
- public void setReview(String review) {
- this.review = review;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/NamedQueryPerformanceTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/NamedQueryPerformanceTest.java
deleted file mode 100644
index 26b8734dc..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/NamedQueryPerformanceTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import org.hibernate.Session;
-
-import javax.persistence.EntityManager;
-
-/**
- * @author Vlad Mihalcea
- */
-public class NamedQueryPerformanceTest extends PlanCacheSizePerformanceTest {
-
- public static final String QUERY_NAME_1 = "findPostCommentSummary";
- public static final String QUERY_NAME_2 = "findPostComments";
-
- public NamedQueryPerformanceTest(int planCacheMaxSize) {
- super(planCacheMaxSize);
- }
-
- @Override
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- entityManagerFactory().addNamedQuery(QUERY_NAME_1, createEntityQuery1(entityManager));
- entityManagerFactory().addNamedQuery(QUERY_NAME_2, createEntityQuery2(entityManager));
- });
- }
-
- @Override
- protected Object getEntityQuery1(EntityManager entityManager) {
- Session session = entityManager.unwrap(Session.class);
- return session.getNamedQuery(QUERY_NAME_1);
- }
-
- @Override
- protected Object getEntityQuery2(EntityManager entityManager) {
- Session session = entityManager.unwrap(Session.class);
- return session.getNamedQuery(QUERY_NAME_2);
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/NaturalIdTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/NaturalIdTest.java
deleted file mode 100644
index b5493b226..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/NaturalIdTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
-import org.hibernate.Session;
-import org.hibernate.annotations.NaturalId;
-import org.junit.Test;
-
-import javax.persistence.*;
-import java.util.List;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-
-/**
- * @author Vlad Mihalcea
- */
-public class NaturalIdTest extends AbstractPostgreSQLIntegrationTest {
-
- @Override
- protected Class>[] entities() {
- return new Class>[]{
- Post.class
- };
- }
-
-
- @Override
- public void init() {
- super.init();
- doInJPA(entityManager -> {
- Post post = new Post();
- post.setTitle(String.format("Post nr. %d", 1));
- post.setSlug("high-performance-java-persistence");
- entityManager.persist(post);
- });
- }
-
- @Test
- public void testFindByNaturalId() {
- doInJPA(entityManager -> {
- String slug = "high-performance-java-persistence";
- Session session = entityManager.unwrap(Session.class);
- Post post = session.bySimpleNaturalId(Post.class).load(slug);
- assertNotNull(post);
- });
- }
-
- @Test
- public void testFindWithQuery() {
- doInJPA(entityManager -> {
- List posts = entityManager.createQuery(
- "select p " +
- "from Post p " +
- "where p.slug is not null", Post.class)
- .getResultList();
- assertFalse(posts.isEmpty());
- });
- }
-
- @Test
- public void testGetReferenceByNaturalId() {
- doInJPA(entityManager -> {
- String slug = "high-performance-java-persistence";
- Session session = entityManager.unwrap(Session.class);
- LOGGER.info("Loading a post by natural identifier");
- Post post = session.bySimpleNaturalId(Post.class).getReference(slug);
- LOGGER.info("Proxy is loaded");
- LOGGER.info("Post title is {}", post.getTitle());
- assertNotNull(post);
- });
- }
-
- @Entity(name = "Post") @Table(name = "post")
- public static class Post {
-
- @Id
- @GeneratedValue
- private Long id;
-
- private String title;
-
- @NaturalId
- @Column(nullable = false, unique = true)
- private String slug;
-
- 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 getSlug() {
- return slug;
- }
-
- public void setSlug(String slug) {
- this.slug = slug;
- }
- }
-}
diff --git a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/PlanCacheSizePerformanceTest.java b/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/PlanCacheSizePerformanceTest.java
deleted file mode 100644
index aca6a2883..000000000
--- a/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/fetching/PlanCacheSizePerformanceTest.java
+++ /dev/null
@@ -1,398 +0,0 @@
-package com.vladmihalcea.book.hpjp.hibernate.fetching;
-
-import com.codahale.metrics.MetricRegistry;
-import com.codahale.metrics.Slf4jReporter;
-import com.codahale.metrics.Timer;
-import com.codahale.metrics.UniformReservoir;
-import com.vladmihalcea.book.hpjp.util.AbstractTest;
-import org.hibernate.SQLQuery;
-import org.hibernate.jpa.QueryHints;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
-import javax.persistence.*;
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.LongStream;
-
-/**
- * @author Vlad Mihalcea
- */
-@RunWith(Parameterized.class)
-public class PlanCacheSizePerformanceTest extends AbstractTest {
-
- private MetricRegistry metricRegistry = new MetricRegistry();
-
- private Timer timer = new Timer(new UniformReservoir(10000));
-
- private Slf4jReporter logReporter = Slf4jReporter
- .forRegistry(metricRegistry)
- .outputTo(LOGGER)
- .convertDurationsTo(TimeUnit.MICROSECONDS)
- .build();
-
- private final int planCacheMaxSize;
-
- public PlanCacheSizePerformanceTest(int planCacheMaxSize) {
- this.planCacheMaxSize = planCacheMaxSize;
- }
-
- @Parameterized.Parameters
- public static Collection rdbmsDataSourceProvider() {
- List