blog: Refactoring, DTO projection, native queries.

Change-Id: Ie073cbe0f4e3da88af7cfb062f6c18d8f5c39df2
diff --git a/blog/src/main/java/eu/mulk/demos/blog/DemoDataLoader.java b/blog/src/main/java/eu/mulk/demos/blog/DemoDataLoader.java
index cbaed9a..bbd5cb0 100644
--- a/blog/src/main/java/eu/mulk/demos/blog/DemoDataLoader.java
+++ b/blog/src/main/java/eu/mulk/demos/blog/DemoDataLoader.java
@@ -1,7 +1,12 @@
 package eu.mulk.demos.blog;
 
 import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toSet;
 
+import eu.mulk.demos.blog.authors.Author;
+import eu.mulk.demos.blog.comments.Comment;
+import eu.mulk.demos.blog.posts.Category;
+import eu.mulk.demos.blog.posts.Post;
 import io.quarkus.runtime.StartupEvent;
 import java.util.stream.Stream;
 import javax.enterprise.context.ApplicationScoped;
@@ -47,7 +52,7 @@
       post.comments =
           nat(COMMENT_COUNT)
               .map(x -> Comment.create(post, "Anonymous Coward", "First post"))
-              .collect(toList());
+              .collect(toSet());
       post.comments.forEach(em::persist);
     }
 
@@ -55,7 +60,7 @@
     var categories =
         nat(CATEGORY_COUNT)
             .map(x -> Category.create("Category #%d".formatted(x)))
-            .collect(toList());
+            .collect(toSet());
     categories.forEach(em::persist);
     for (var post : posts) {
       post.categories = categories;
diff --git a/blog/src/main/java/eu/mulk/demos/blog/PostResource.java b/blog/src/main/java/eu/mulk/demos/blog/PostResource.java
deleted file mode 100644
index 532e873..0000000
--- a/blog/src/main/java/eu/mulk/demos/blog/PostResource.java
+++ /dev/null
@@ -1,138 +0,0 @@
-package eu.mulk.demos.blog;
-
-import java.util.List;
-import java.util.Set;
-import javax.transaction.Transactional;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import org.hibernate.annotations.LazyToOne;
-import org.hibernate.annotations.LazyToOneOption;
-import org.jboss.logging.Logger;
-
-@Path("/posts")
-public class PostResource {
-
-  static final Logger log = Logger.getLogger(PostResource.class);
-
-  /**
-   * Fetches all posts with no extra information.
-   *
-   * Simple.  No surprises.
-   */
-  @GET
-  @Produces(MediaType.TEXT_PLAIN)
-  @Transactional
-  public List<Post> getAll() {
-    clearLog();
-
-    return Post.findAll().list();
-  }
-
-  /**
-   * Fetches all posts with comments included.
-   *
-   * Lazy fetching.  Simple.  No surprises.
-   */
-  @GET
-  @Produces(MediaType.TEXT_PLAIN)
-  @Transactional
-  @Path("/q1")
-  public List<Post> getAllWithComments() {
-    clearLog();
-
-    return Post.find(
-        """
-            SELECT p FROM Post p
-              LEFT JOIN FETCH p.comments 
-            """)
-        .list();
-  }
-
-  /**
-   * Fetches all posts with author info included.
-   *
-   * <strong>Oops!</strong>
-   *
-   * {@link LazyToOne} with {@link LazyToOneOption#NO_PROXY} is needed to make this efficient.
-   */
-  @GET
-  @Produces(MediaType.TEXT_PLAIN)
-  @Transactional
-  @Path("/q2")
-  public List<Post> getAllWithAuthors() {
-    clearLog();
-
-    return Post.find(
-        """
-            SELECT p FROM Post p
-              LEFT JOIN FETCH p.author 
-            """)
-        .list();
-  }
-
-  /**
-   * Fetches all posts with comments and category info included.
-   *
-   * <strong>Oops!</strong>  Crashes.
-   *
-   * Either use {@link Set} and get bad performance or do it as in {@link
-   * #getAllWithCommentsAndCategories2()}.
-   */
-  @GET
-  @Produces(MediaType.TEXT_PLAIN)
-  @Transactional
-  @Path("/q3")
-  public List<Post> getAllWithCommentsAndCategories() {
-    clearLog();
-
-    return Post.find(
-        """
-            SELECT p FROM Post p
-              LEFT JOIN FETCH p.comments
-              LEFT JOIN FETCH p.categories
-            """)
-        .list();
-  }
-
-  /**
-   * Fetches all posts with comments and category info included.
-   *
-   * 2 queries, but hey, no cartesian explosion!  Works really well.
-   */
-  @GET
-  @Produces(MediaType.TEXT_PLAIN)
-  @Transactional
-  @Path("/q4")
-  public List<Post> getAllWithCommentsAndCategories2() {
-    clearLog();
-
-    List<Post> posts = Post.find(
-        """
-            SELECT p FROM Post p
-              LEFT JOIN FETCH p.comments
-            """)
-        .list();
-
-    posts = Post.find(
-        """
-            SELECT DISTINCT p FROM Post p
-              LEFT JOIN FETCH p.categories
-             WHERE p IN (?1)
-            """,
-        posts)
-        .list();
-
-    return posts;
-  }
-
-  private static void clearLog() {
-    log.infof("""
-                
-        -----------------------------------------------------
-        -------------------- NEW REQUEST --------------------
-        -----------------------------------------------------
-        """);
-  }
-}
diff --git a/blog/src/main/java/eu/mulk/demos/blog/Author.java b/blog/src/main/java/eu/mulk/demos/blog/authors/Author.java
similarity index 84%
rename from blog/src/main/java/eu/mulk/demos/blog/Author.java
rename to blog/src/main/java/eu/mulk/demos/blog/authors/Author.java
index d544d2e..e3c936f 100644
--- a/blog/src/main/java/eu/mulk/demos/blog/Author.java
+++ b/blog/src/main/java/eu/mulk/demos/blog/authors/Author.java
@@ -1,6 +1,7 @@
-package eu.mulk.demos.blog;
+package eu.mulk.demos.blog.authors;
 
 import io.quarkus.hibernate.orm.panache.PanacheEntity;
+import javax.json.bind.annotation.JsonbTransient;
 import javax.persistence.Entity;
 import javax.persistence.FetchType;
 import javax.persistence.OneToOne;
@@ -14,6 +15,7 @@
 
   @OneToOne(fetch = FetchType.LAZY, mappedBy = "author")
   @LazyToOne(LazyToOneOption.NO_PROXY)
+  @JsonbTransient
   public BasicCredentials basicCredentials;
 
   public static Author create(String name) {
diff --git a/blog/src/main/java/eu/mulk/demos/blog/BasicCredentials.java b/blog/src/main/java/eu/mulk/demos/blog/authors/BasicCredentials.java
similarity index 85%
rename from blog/src/main/java/eu/mulk/demos/blog/BasicCredentials.java
rename to blog/src/main/java/eu/mulk/demos/blog/authors/BasicCredentials.java
index 01471c6..92e7a37 100644
--- a/blog/src/main/java/eu/mulk/demos/blog/BasicCredentials.java
+++ b/blog/src/main/java/eu/mulk/demos/blog/authors/BasicCredentials.java
@@ -1,6 +1,7 @@
-package eu.mulk.demos.blog;
+package eu.mulk.demos.blog.authors;
 
 import io.quarkus.hibernate.orm.panache.PanacheEntity;
+import javax.json.bind.annotation.JsonbTransient;
 import javax.persistence.Entity;
 import javax.persistence.FetchType;
 import javax.persistence.MapsId;
@@ -11,6 +12,7 @@
 
   @OneToOne(fetch = FetchType.LAZY)
   @MapsId
+  @JsonbTransient
   public Author author;
 
   public String username;
diff --git a/blog/src/main/java/eu/mulk/demos/blog/Comment.java b/blog/src/main/java/eu/mulk/demos/blog/comments/Comment.java
similarity index 67%
rename from blog/src/main/java/eu/mulk/demos/blog/Comment.java
rename to blog/src/main/java/eu/mulk/demos/blog/comments/Comment.java
index 251d6d8..415ac7b 100644
--- a/blog/src/main/java/eu/mulk/demos/blog/Comment.java
+++ b/blog/src/main/java/eu/mulk/demos/blog/comments/Comment.java
@@ -1,10 +1,14 @@
-package eu.mulk.demos.blog;
+package eu.mulk.demos.blog.comments;
 
+import eu.mulk.demos.blog.posts.Post;
 import io.quarkus.hibernate.orm.panache.PanacheEntity;
 import java.time.Instant;
 import javax.json.bind.annotation.JsonbTransient;
 import javax.persistence.Column;
 import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.FetchType;
 import javax.persistence.ManyToOne;
 
 @Entity
@@ -14,11 +18,14 @@
 
   public Instant publicationDate;
 
+  @Enumerated(EnumType.STRING)
+  public SpamStatus spamStatus;
+
   @Column(columnDefinition = "TEXT")
   public String text;
 
+  @ManyToOne(fetch = FetchType.LAZY)
   @JsonbTransient
-  @ManyToOne
   public Post post;
 
   public static Comment create(Post post, String authorName, String text) {
@@ -27,6 +34,8 @@
     c.publicationDate = Instant.now();
     c.text = text;
     c.post = post;
+    c.spamStatus = SpamStatus.UNKNOWN;
     return c;
   }
+
 }
diff --git a/blog/src/main/java/eu/mulk/demos/blog/comments/SpamAssessmentService.java b/blog/src/main/java/eu/mulk/demos/blog/comments/SpamAssessmentService.java
new file mode 100644
index 0000000..efa9ac2
--- /dev/null
+++ b/blog/src/main/java/eu/mulk/demos/blog/comments/SpamAssessmentService.java
@@ -0,0 +1,33 @@
+package eu.mulk.demos.blog.comments;
+
+import static java.util.stream.Collectors.toMap;
+
+import java.util.Collection;
+import java.util.Map;
+import javax.enterprise.context.ApplicationScoped;
+
+/**
+ * Simulates a remote service that classifies {@link Comment}s as either {@link SpamStatus#SPAM} or
+ * {@link SpamStatus#HAM}.
+ */
+@ApplicationScoped
+public class SpamAssessmentService {
+
+  /**
+   * Classifies a list of {@link Comment}s as either {@link SpamStatus#SPAM} or * {@link
+   * SpamStatus#HAM}.
+   *
+   * @return a map mapping {@link Comment#id}s to {@link SpamStatus}es.
+   */
+  public Map<Long, SpamStatus> assess(Collection<Comment> comments) {
+    return comments.stream().collect(toMap(x -> x.id, this::assessOne));
+  }
+
+  private SpamStatus assessOne(Comment c) {
+    if (c.authorName.startsWith("Anonymous")) {
+      return SpamStatus.SPAM;
+    }
+
+    return SpamStatus.HAM;
+  }
+}
diff --git a/blog/src/main/java/eu/mulk/demos/blog/comments/SpamStatus.java b/blog/src/main/java/eu/mulk/demos/blog/comments/SpamStatus.java
new file mode 100644
index 0000000..a5cd7ee
--- /dev/null
+++ b/blog/src/main/java/eu/mulk/demos/blog/comments/SpamStatus.java
@@ -0,0 +1,7 @@
+package eu.mulk.demos.blog.comments;
+
+public enum SpamStatus {
+  UNKNOWN,
+  HAM,
+  SPAM,
+}
diff --git a/blog/src/main/java/eu/mulk/demos/blog/Category.java b/blog/src/main/java/eu/mulk/demos/blog/posts/Category.java
similarity index 89%
rename from blog/src/main/java/eu/mulk/demos/blog/Category.java
rename to blog/src/main/java/eu/mulk/demos/blog/posts/Category.java
index 0959d18..5870010 100644
--- a/blog/src/main/java/eu/mulk/demos/blog/Category.java
+++ b/blog/src/main/java/eu/mulk/demos/blog/posts/Category.java
@@ -1,4 +1,4 @@
-package eu.mulk.demos.blog;
+package eu.mulk.demos.blog.posts;
 
 import io.quarkus.hibernate.orm.panache.PanacheEntity;
 import javax.persistence.Entity;
diff --git a/blog/src/main/java/eu/mulk/demos/blog/Post.java b/blog/src/main/java/eu/mulk/demos/blog/posts/Post.java
similarity index 72%
rename from blog/src/main/java/eu/mulk/demos/blog/Post.java
rename to blog/src/main/java/eu/mulk/demos/blog/posts/Post.java
index 3ae3fa0..6fb2c11 100644
--- a/blog/src/main/java/eu/mulk/demos/blog/Post.java
+++ b/blog/src/main/java/eu/mulk/demos/blog/posts/Post.java
@@ -1,8 +1,11 @@
-package eu.mulk.demos.blog;
+package eu.mulk.demos.blog.posts;
 
+import eu.mulk.demos.blog.authors.Author;
+import eu.mulk.demos.blog.comments.Comment;
 import io.quarkus.hibernate.orm.panache.PanacheEntity;
 import java.time.Instant;
-import java.util.List;
+import java.util.Set;
+import javax.json.bind.annotation.JsonbTransient;
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.FetchType;
@@ -21,13 +24,16 @@
   public String body;
 
   @ManyToOne(fetch = FetchType.LAZY)
+  @JsonbTransient
   public Author author;
 
   @ManyToMany(fetch = FetchType.LAZY)
-  public List<Category> categories;
+  @JsonbTransient
+  public Set<Category> categories;
 
   @OneToMany(fetch = FetchType.LAZY, mappedBy = "post")
-  public List<Comment> comments;
+  @JsonbTransient
+  public Set<Comment> comments;
 
   public static Post create(Author author, String title) {
     var p = new Post();
diff --git a/blog/src/main/java/eu/mulk/demos/blog/posts/PostResource.java b/blog/src/main/java/eu/mulk/demos/blog/posts/PostResource.java
new file mode 100644
index 0000000..ae8b4de
--- /dev/null
+++ b/blog/src/main/java/eu/mulk/demos/blog/posts/PostResource.java
@@ -0,0 +1,248 @@
+package eu.mulk.demos.blog.posts;
+
+import eu.mulk.demos.blog.authors.Author;
+import eu.mulk.demos.blog.comments.Comment;
+import eu.mulk.demos.blog.comments.SpamAssessmentService;
+import eu.mulk.demos.blog.comments.SpamStatus;
+import java.util.List;
+import java.util.Set;
+import javax.inject.Inject;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.transaction.Transactional;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import org.hibernate.annotations.LazyToOne;
+import org.hibernate.annotations.LazyToOneOption;
+import org.jboss.logging.Logger;
+
+@Path("/posts")
+@Produces(MediaType.APPLICATION_JSON)
+public class PostResource {
+
+  static final Logger log = Logger.getLogger(PostResource.class);
+
+  @Inject
+  SpamAssessmentService spamAssessmentService;
+
+  @PersistenceContext
+  EntityManager entityManager;
+
+  /**
+   * Fetches all posts with no extra information.
+   *
+   * Simple.  No surprises.
+   */
+  @GET
+  @Transactional
+  public List<Post> getAll() {
+    clearLog();
+
+    return Post.findAll().list();
+  }
+
+  /**
+   * Fetches all posts with comments included.
+   *
+   * Lazy fetching.  Simple.  No surprises.
+   */
+  @GET
+  @Transactional
+  @Path("/q1")
+  public List<Post> getAllWithComments() {
+    clearLog();
+
+    return Post.find(
+        """
+            SELECT p FROM Post p
+              LEFT JOIN FETCH p.comments 
+            """)
+        .list();
+  }
+
+  /**
+   * Fetches all posts with author info included.
+   *
+   * <strong>Oops!</strong>
+   *
+   * {@link LazyToOne} with {@link LazyToOneOption#NO_PROXY} on {@link Author#basicCredentials} is
+   * needed to make this efficient.
+   */
+  @GET
+  @Transactional
+  @Path("/q2")
+  public List<Post> getAllWithAuthors() {
+    clearLog();
+
+    return Post.find(
+        """
+            SELECT p FROM Post p
+              LEFT JOIN FETCH p.author 
+            """)
+        .list();
+  }
+
+  /**
+   * Fetches all posts with comments and category info included.
+   *
+   * <strong>Oops!</strong>  Crashes.
+   *
+   * Either use {@link Set} and get bad performance or do it as in {@link
+   * #getAllWithCommentsAndCategories2()}.
+   */
+  @GET
+  @Transactional
+  @Path("/q3")
+  public List<Post> getAllWithCommentsAndCategories() {
+    clearLog();
+
+    return Post.find(
+        """
+            SELECT p FROM Post p
+              LEFT JOIN FETCH p.comments
+              LEFT JOIN FETCH p.categories
+            """)
+        .list();
+  }
+
+  /**
+   * Fetches all posts with comments and category info included.
+   *
+   * 2 queries, but hey, no cartesian explosion!  Works really well.
+   */
+  @GET
+  @Transactional
+  @Path("/q4")
+  public List<Post> getAllWithCommentsAndCategories2() {
+    clearLog();
+
+    List<Post> posts = Post.find(
+        """
+            SELECT p FROM Post p
+              LEFT JOIN FETCH p.comments
+            """)
+        .list();
+
+    posts = Post.find(
+        """
+            SELECT DISTINCT p FROM Post p
+              LEFT JOIN FETCH p.categories
+             WHERE p IN (?1)
+            """,
+        posts)
+        .list();
+
+    return posts;
+  }
+
+  /**
+   * Fetches all posts with comments and category info included.
+   *
+   * 2 queries, but hey, no cartesian explosion!  Works really well.
+   */
+  @POST
+  @Transactional
+  @Path("/q5")
+  public void updateCommentStatus() {
+    clearLog();
+
+    List<Comment> comments = Comment.find(
+        """
+            SELECT c FROM Comment c
+             WHERE c.spamStatus = 'UNKNOWN'
+            """)
+        .list();
+
+    var assessments = spamAssessmentService.assess(comments);
+
+    for (var assessment : assessments.entrySet()) {
+      Comment comment = Comment.findById(assessment.getKey());
+      comment.spamStatus = assessment.getValue();
+    }
+  }
+
+  /**
+   * Resets the {@link Comment#spamStatus} to {@link SpamStatus#UNKNOWN} on all comments.
+   *
+   * This issues a lot of UPDATE statements, but semantically speaking it works.
+   */
+  @POST
+  @Transactional
+  @Path("/q6")
+  public void resetCommentStatus() {
+    clearLog();
+
+    List<Comment> comments = Comment.find(
+        """
+            SELECT c FROM Comment c
+             WHERE c.spamStatus <> 'UNKNOWN'
+            """)
+        .list();
+    comments.forEach(c -> c.spamStatus = SpamStatus.UNKNOWN);
+  }
+
+  /**
+   * Resets the {@link Comment#spamStatus} to {@link SpamStatus#UNKNOWN} on all comments.
+   *
+   * This is exactly equivalent to {@link #resetCommentStatus()} and just as efficient or
+   * inefficient.
+   */
+  @POST
+  @Transactional
+  @Path("/q6")
+  public void resetCommentStatus2() {
+    clearLog();
+
+    Comment.update("UPDATE Comment c SET c.spamStatus = 'UNKNOWN' WHERE c.spamStatus <> 'UNKNOWN'");
+  }
+
+  /**
+   * Resets the {@link Comment#spamStatus} to {@link SpamStatus#UNKNOWN} on all comments.
+   *
+   * This is exactly equivalent to {@link #resetCommentStatus()} and just as efficient or
+   * inefficient.
+   */
+  @POST
+  @Transactional
+  @Path("/q7")
+  public void resetCommentStatus3() {
+    clearLog();
+
+    entityManager.createNativeQuery(
+        "UPDATE comment SET spam_status = 'UNKNOWN' WHERE spam_status <> 'UNKNOWN'")
+        .executeUpdate();
+  }
+
+  /**
+   * Fetches all posts with all the relevant info for an overview included.
+   */
+  @GET
+  @Transactional
+  @Path("/q8")
+  @Produces(MediaType.APPLICATION_JSON)
+  public List<PostSummary> overview() {
+    clearLog();
+
+    return entityManager.createQuery(
+        """
+            SELECT NEW eu.mulk.demos.blog.posts.PostSummary(
+                p.author.name, p.title, p.publicationDate, size(p.comments))
+              FROM Post p
+            """,
+        PostSummary.class)
+        .getResultList();
+  }
+
+  private static void clearLog() {
+    log.infof("""
+                
+        -----------------------------------------------------
+        -------------------- NEW REQUEST --------------------
+        -----------------------------------------------------
+        """);
+  }
+
+}
diff --git a/blog/src/main/java/eu/mulk/demos/blog/posts/PostSummary.java b/blog/src/main/java/eu/mulk/demos/blog/posts/PostSummary.java
new file mode 100644
index 0000000..f6ad3ec
--- /dev/null
+++ b/blog/src/main/java/eu/mulk/demos/blog/posts/PostSummary.java
@@ -0,0 +1,22 @@
+package eu.mulk.demos.blog.posts;
+
+import java.time.Instant;
+
+public final class PostSummary {
+
+  public final String authorName;
+  public final String title;
+  public final Instant publicationDate;
+  public final int commentCount;
+
+  public PostSummary(
+      String authorName,
+      String title,
+      Instant publicationDate,
+      int commentCount) {
+    this.authorName = authorName;
+    this.title = title;
+    this.publicationDate = publicationDate;
+    this.commentCount = commentCount;
+  }
+}
diff --git a/blog/src/main/resources/application.properties b/blog/src/main/resources/application.properties
index fbf150e..e8b4aaf 100644
--- a/blog/src/main/resources/application.properties
+++ b/blog/src/main/resources/application.properties
@@ -5,9 +5,15 @@
 %dev.quarkus.datasource.username = demo
 %dev.quarkus.datasource.password =
 
+quarkus.hibernate-orm.physical-naming-strategy = com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy
+quarkus.hibernate-orm.dialect = io.quarkus.hibernate.orm.runtime.dialect.QuarkusPostgreSQL10Dialect
+
 %dev.quarkus.hibernate-orm.log.sql = true
 %dev.quarkus.hibernate-orm.log.format-sql = true
 %dev.quarkus.hibernate-orm.database.generation = drop-and-create
+%dev.quarkus.hibernate-orm.database.generation.create-schemas = true
 
-quarkus.hibernate-orm.physical-naming-strategy = com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy
-quarkus.hibernate-orm.dialect = io.quarkus.hibernate.orm.runtime.dialect.QuarkusPostgreSQL10Dialect
+quarkus.hibernate-orm.jdbc.statement-batch-size = 200
+quarkus.hibernate-orm.jdbc.statement-fetch-size = 1000
+quarkus.hibernate-orm.fetch.batch-size = 200
+quarkus.hibernate-orm.fetch.max-depth = 5