orderLines, boolean eligibleForSpecialDiscount) {
+ super(orderLines);
+ this.eligibleForExtraDiscount = eligibleForSpecialDiscount;
+ }
+
+ public boolean isEligibleForExtraDiscount() {
+ return eligibleForExtraDiscount;
+ }
+
+ @Override
+ protected double applyDiscountPolicy(SpecialDiscountPolicy discountPolicy) {
+ return discountPolicy.discount(this);
+ }
+
+ @Override
+ public void accept(OrderVisitor visitor) {
+ visitor.visit(this);
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java b/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java
new file mode 100644
index 0000000000..ea23cdaa4b
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java
@@ -0,0 +1,24 @@
+package com.baeldung.ddd.order.doubledispatch.visitor;
+
+import com.baeldung.ddd.order.doubledispatch.Order;
+import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
+
+public class HtmlOrderViewCreator implements OrderVisitor {
+
+ private String html;
+
+ public String getHtml() {
+ return html;
+ }
+
+ @Override
+ public void visit(Order order) {
+ html = String.format("Regular order total cost: %s
", order.totalCost());
+ }
+
+ @Override
+ public void visit(SpecialOrder order) {
+ html = String.format("Special Order
total cost: %s
", order.totalCost());
+ }
+
+}
diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java b/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java
new file mode 100644
index 0000000000..00f0740f6e
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java
@@ -0,0 +1,9 @@
+package com.baeldung.ddd.order.doubledispatch.visitor;
+
+import com.baeldung.ddd.order.doubledispatch.Order;
+import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
+
+public interface OrderVisitor {
+ void visit(Order order);
+ void visit(SpecialOrder order);
+}
diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java b/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java
new file mode 100644
index 0000000000..1628718d9b
--- /dev/null
+++ b/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java
@@ -0,0 +1,5 @@
+package com.baeldung.ddd.order.doubledispatch.visitor;
+
+public interface Visitable {
+ void accept(V visitor);
+}
diff --git a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java b/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java
index ed11b0dca4..81ae3bbd19 100644
--- a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java
+++ b/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java
@@ -92,7 +92,7 @@ class JpaOrder {
}
void removeLineItem(int line) {
- JpaOrderLine removedLine = orderLines.remove(line);
+ orderLines.remove(line);
}
void setCurrencyUnit(String currencyUnit) {
diff --git a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java b/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java
index 61e67fa12a..1d2ae5230a 100644
--- a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java
+++ b/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java
@@ -15,7 +15,7 @@ class JpaProduct {
public JpaProduct(BigDecimal price, String currencyUnit) {
super();
this.price = price;
- currencyUnit = currencyUnit;
+ this.currencyUnit = currencyUnit;
}
@Override
diff --git a/ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java b/ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java
new file mode 100644
index 0000000000..2b0e0b1997
--- /dev/null
+++ b/ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java
@@ -0,0 +1,17 @@
+package com.baeldung.ddd.order;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.joda.money.CurrencyUnit;
+import org.joda.money.Money;
+
+public class OrderFixtureUtils {
+ public static List anyOrderLines() {
+ return Arrays.asList(new OrderLine(new Product(Money.of(CurrencyUnit.USD, 100)), 1));
+ }
+
+ public static List orderLineItemsWorthNDollars(int totalCost) {
+ return Arrays.asList(new OrderLine(new Product(Money.of(CurrencyUnit.USD, totalCost)), 1));
+ }
+}
diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java b/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java
new file mode 100644
index 0000000000..0ec73415d3
--- /dev/null
+++ b/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java
@@ -0,0 +1,77 @@
+package com.baeldung.ddd.order.doubledispatch;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.joda.money.CurrencyUnit;
+import org.joda.money.Money;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.ddd.order.OrderFixtureUtils;
+
+public class DoubleDispatchDiscountPolicyUnitTest {
+ // @formatter:off
+ @DisplayName(
+ "given regular order with items worth $100 total, " +
+ "when apply 10% discount policy, " +
+ "then cost after discount is $90"
+ )
+ // @formatter:on
+ @Test
+ void test() throws Exception {
+ // given
+ Order order = new Order(OrderFixtureUtils.orderLineItemsWorthNDollars(100));
+ SpecialDiscountPolicy discountPolicy = new SpecialDiscountPolicy() {
+
+ @Override
+ public double discount(Order order) {
+ return 0.10;
+ }
+
+ @Override
+ public double discount(SpecialOrder order) {
+ return 0;
+ }
+ };
+
+ // when
+ Money totalCostAfterDiscount = order.totalCost(discountPolicy);
+
+ // then
+ assertThat(totalCostAfterDiscount).isEqualTo(Money.of(CurrencyUnit.USD, 90));
+ }
+
+ // @formatter:off
+ @DisplayName(
+ "given special order eligible for extra discount with items worth $100 total, " +
+ "when apply 20% discount policy for extra discount orders, " +
+ "then cost after discount is $80"
+ )
+ // @formatter:on
+ @Test
+ void test1() throws Exception {
+ // given
+ boolean eligibleForExtraDiscount = true;
+ Order order = new SpecialOrder(OrderFixtureUtils.orderLineItemsWorthNDollars(100), eligibleForExtraDiscount);
+ SpecialDiscountPolicy discountPolicy = new SpecialDiscountPolicy() {
+
+ @Override
+ public double discount(Order order) {
+ return 0;
+ }
+
+ @Override
+ public double discount(SpecialOrder order) {
+ if (order.isEligibleForExtraDiscount())
+ return 0.20;
+ return 0.10;
+ }
+ };
+
+ // when
+ Money totalCostAfterDiscount = order.totalCost(discountPolicy);
+
+ // then
+ assertThat(totalCostAfterDiscount).isEqualTo(Money.of(CurrencyUnit.USD, 80.00));
+ }
+}
diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java b/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java
new file mode 100644
index 0000000000..e360c1c76a
--- /dev/null
+++ b/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.ddd.order.doubledispatch;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.ddd.order.doubledispatch.Order;
+import com.baeldung.ddd.order.OrderFixtureUtils;
+import com.baeldung.ddd.order.OrderLine;
+import com.baeldung.ddd.order.doubledispatch.visitor.HtmlOrderViewCreator;
+
+public class HtmlOrderViewCreatorUnitTest {
+ // @formatter:off
+ @DisplayName(
+ "given collection of regular and special orders, " +
+ "when create HTML view using visitor for each order, " +
+ "then the dedicated view is created for each order"
+ )
+ // @formatter:on
+ @Test
+ void test() throws Exception {
+ // given
+ List anyOrderLines = OrderFixtureUtils.anyOrderLines();
+ List orders = Arrays.asList(new Order(anyOrderLines), new SpecialOrder(anyOrderLines));
+ HtmlOrderViewCreator htmlOrderViewCreator = new HtmlOrderViewCreator();
+
+ // when
+ orders.get(0)
+ .accept(htmlOrderViewCreator);
+ String regularOrderHtml = htmlOrderViewCreator.getHtml();
+ orders.get(1)
+ .accept(htmlOrderViewCreator);
+ String specialOrderHtml = htmlOrderViewCreator.getHtml();
+
+ // then
+ assertThat(regularOrderHtml).containsPattern("Regular order total cost: .*
");
+ assertThat(specialOrderHtml).containsPattern("Special Order
total cost: .*
");
+ }
+}
diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java b/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java
new file mode 100644
index 0000000000..3d135e9dbe
--- /dev/null
+++ b/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java
@@ -0,0 +1,50 @@
+package com.baeldung.ddd.order.doubledispatch;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.ddd.order.doubledispatch.Order;
+import com.baeldung.ddd.order.OrderFixtureUtils;
+import com.baeldung.ddd.order.OrderLine;
+import com.baeldung.ddd.order.doubledispatch.SpecialDiscountPolicy;
+import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
+
+public class MethodOverloadExampleUnitTest {
+// @formatter:off
+@DisplayName(
+ "given discount policy accepting special orders, " +
+ "when apply the policy on special order declared as regular order, " +
+ "then regular discount method is used"
+ )
+// @formatter:on
+ @Test
+ void test() throws Exception {
+ // given
+ SpecialDiscountPolicy specialPolicy = new SpecialDiscountPolicy() {
+ @Override
+ public double discount(Order order) {
+ return 0.01;
+ }
+
+ @Override
+ public double discount(SpecialOrder order) {
+ return 0.10;
+ }
+ };
+ Order specialOrder = new SpecialOrder(anyOrderLines());
+
+ // when
+ double discount = specialPolicy.discount(specialOrder);
+
+ // then
+ assertThat(discount).isEqualTo(0.01);
+ }
+
+ private List anyOrderLines() {
+ return OrderFixtureUtils.anyOrderLines();
+ }
+}
diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java b/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java
new file mode 100644
index 0000000000..82e074d028
--- /dev/null
+++ b/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java
@@ -0,0 +1,37 @@
+package com.baeldung.ddd.order.doubledispatch;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.ddd.order.OrderFixtureUtils;
+
+public class SingleDispatchDiscountPolicyUnitTest {
+ // @formatter:off
+ @DisplayName(
+ "given two discount policies, " +
+ "when use these policies, " +
+ "then single dispatch chooses the implementation based on runtime type"
+ )
+ // @formatter:on
+ @Test
+ void test() throws Exception {
+ // given
+ DiscountPolicy flatPolicy = new FlatDiscountPolicy();
+ DiscountPolicy amountPolicy = new AmountBasedDiscountPolicy();
+ Order orderWorth501Dollars = orderWorthNDollars(501);
+
+ // when
+ double flatDiscount = flatPolicy.discount(orderWorth501Dollars);
+ double amountDiscount = amountPolicy.discount(orderWorth501Dollars);
+
+ // then
+ assertThat(flatDiscount).isEqualTo(0.01);
+ assertThat(amountDiscount).isEqualTo(0.1);
+ }
+
+ private Order orderWorthNDollars(int totalCost) {
+ return new Order(OrderFixtureUtils.orderLineItemsWorthNDollars(totalCost));
+ }
+}
diff --git a/guava-collections-set/README.md b/guava-collections-set/README.md
new file mode 100644
index 0000000000..c36d9e0b61
--- /dev/null
+++ b/guava-collections-set/README.md
@@ -0,0 +1,8 @@
+# Guava
+
+## Relevant Articles:
+
+- [Guava – Sets](http://www.baeldung.com/guava-sets)
+- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
+- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
+- [Guide to Guava Multiset](https://www.baeldung.com/guava-multiset)
diff --git a/guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSet.java b/guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSet.java
similarity index 93%
rename from guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSet.java
rename to guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSet.java
index 1d19423f7e..f474fcb17b 100644
--- a/guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSet.java
+++ b/guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSet.java
@@ -1,14 +1,9 @@
package org.baeldung.guava;
-import java.util.AbstractMap;
-import java.util.AbstractSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.WeakHashMap;
-
import com.google.common.base.Function;
+import java.util.*;
+
public class GuavaMapFromSet extends AbstractMap {
private class SingleEntry implements Entry {
diff --git a/guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java b/guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java
similarity index 99%
rename from guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java
rename to guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java
index d80f047f5c..03f2d8f891 100644
--- a/guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java
+++ b/guava-collections-set/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java
@@ -1,15 +1,14 @@
package org.baeldung.guava;
-import static org.junit.Assert.assertTrue;
+import com.google.common.base.Function;
+import org.junit.Test;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
-import org.junit.Test;
-
-import com.google.common.base.Function;
+import static org.junit.Assert.assertTrue;
public class GuavaMapFromSetUnitTest {
diff --git a/guava-collections/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java b/guava-collections-set/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java
similarity index 97%
rename from guava-collections/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java
rename to guava-collections-set/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java
index 6f3092d845..edefc61fc4 100644
--- a/guava-collections/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java
+++ b/guava-collections-set/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java
@@ -1,13 +1,12 @@
package org.baeldung.guava;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import org.junit.Test;
import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.Range;
import com.google.common.collect.RangeSet;
import com.google.common.collect.TreeRangeSet;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
public class GuavaRangeSetUnitTest {
@@ -122,6 +121,5 @@ public class GuavaRangeSetUnitTest {
.add(Range.closed(0, 2))
.add(Range.closed(3, 5))
.add(Range.closed(5, 8)).build();
-
}
}
diff --git a/guava-collections-set/src/test/java/org/baeldung/guava/GuavaSetOperationsUnitTest.java b/guava-collections-set/src/test/java/org/baeldung/guava/GuavaSetOperationsUnitTest.java
new file mode 100644
index 0000000000..dfd90ad738
--- /dev/null
+++ b/guava-collections-set/src/test/java/org/baeldung/guava/GuavaSetOperationsUnitTest.java
@@ -0,0 +1,131 @@
+package org.baeldung.guava;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.collect.*;
+import org.junit.Test;
+
+import java.util.List;
+import java.util.Set;
+
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+public class GuavaSetOperationsUnitTest {
+
+ @Test
+ public void whenCalculatingUnionOfSets_thenCorrect() {
+ final Set first = ImmutableSet.of('a', 'b', 'c');
+ final Set second = ImmutableSet.of('b', 'c', 'd');
+
+ final Set union = Sets.union(first, second);
+ assertThat(union, containsInAnyOrder('a', 'b', 'c', 'd'));
+ }
+
+ @Test
+ public void whenCalculatingCartesianProductOfSets_thenCorrect() {
+ final Set first = ImmutableSet.of('a', 'b');
+ final Set second = ImmutableSet.of('c', 'd');
+ final Set> result = Sets.cartesianProduct(ImmutableList.of(first, second));
+
+ final Function, String> func = new Function, String>() {
+ @Override
+ public final String apply(final List input) {
+ return Joiner
+ .on(" ").join(input);
+ }
+ };
+
+ final Iterable joined = Iterables.transform(result, func);
+ assertThat(joined, containsInAnyOrder("a c", "a d", "b c", "b d"));
+ }
+
+ @Test
+ public void whenCalculatingSetIntersection_thenCorrect() {
+ final Set first = ImmutableSet.of('a', 'b', 'c');
+ final Set second = ImmutableSet.of('b', 'c', 'd');
+
+ final Set intersection = Sets.intersection(first, second);
+ assertThat(intersection, containsInAnyOrder('b', 'c'));
+ }
+
+ @Test
+ public void whenCalculatingSetSymmetricDifference_thenCorrect() {
+ final Set first = ImmutableSet.of('a', 'b', 'c');
+ final Set second = ImmutableSet.of('b', 'c', 'd');
+
+ final Set intersection = Sets.symmetricDifference(first, second);
+ assertThat(intersection, containsInAnyOrder('a', 'd'));
+ }
+
+ @Test
+ public void whenCalculatingPowerSet_thenCorrect() {
+ final Set chars = ImmutableSet.of('a', 'b');
+ final Set> result = Sets.powerSet(chars);
+
+ final Set empty = ImmutableSet. builder().build();
+ final Set a = ImmutableSet.of('a');
+ final Set b = ImmutableSet.of('b');
+ final Set aB = ImmutableSet.of('a', 'b');
+
+ assertThat(result, contains(empty, a, b, aB));
+ }
+
+ @Test
+ public void whenCreatingRangeOfIntegersSet_thenCreated() {
+ final int start = 10;
+ final int end = 30;
+ final ContiguousSet set = ContiguousSet.create(Range.closed(start, end), DiscreteDomain.integers());
+
+ assertEquals(21, set.size());
+ assertEquals(10, set.first().intValue());
+ assertEquals(30, set.last().intValue());
+ }
+
+ @Test
+ public void whenUsingRangeSet_thenCorrect() {
+ final RangeSet rangeSet = TreeRangeSet.create();
+ rangeSet.add(Range.closed(1, 10));
+ rangeSet.add(Range.closed(12, 15));
+
+ assertEquals(2, rangeSet.asRanges().size());
+
+ rangeSet.add(Range.closed(10, 12));
+ assertTrue(rangeSet.encloses(Range.closed(1, 15)));
+ assertEquals(1, rangeSet.asRanges().size());
+ }
+
+ @Test
+ public void whenInsertDuplicatesInMultiSet_thenInserted() {
+ final Multiset names = HashMultiset.create();
+ names.add("John");
+ names.add("Adam", 3);
+ names.add("John");
+
+ assertEquals(2, names.count("John"));
+ names.remove("John");
+ assertEquals(1, names.count("John"));
+
+ assertEquals(3, names.count("Adam"));
+ names.remove("Adam", 2);
+ assertEquals(1, names.count("Adam"));
+ }
+
+ @Test
+ public void whenGetTopOcurringElementsWithMultiSet_thenCorrect() {
+ final Multiset names = HashMultiset.create();
+ names.add("John");
+ names.add("Adam", 5);
+ names.add("Jane");
+ names.add("Tom", 2);
+
+ final Set sorted = Multisets.copyHighestCountFirst(names).elementSet();
+ final List topTwo = Lists.newArrayList(sorted).subList(0, 2);
+ assertEquals(2, topTwo.size());
+ assertEquals("Adam", topTwo.get(0));
+ assertEquals("Tom", topTwo.get(1));
+ }
+}
diff --git a/guava-collections/README.md b/guava-collections/README.md
index fc9cf549c3..e919a98c2b 100644
--- a/guava-collections/README.md
+++ b/guava-collections/README.md
@@ -11,13 +11,10 @@
- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection)
- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial)
- [Guava – Lists](http://www.baeldung.com/guava-lists)
-- [Guava – Sets](http://www.baeldung.com/guava-sets)
- [Guava – Maps](http://www.baeldung.com/guava-maps)
- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap)
-- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
-- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)
\ No newline at end of file
diff --git a/guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java
index cb6ec7ef96..ab38afa5c4 100644
--- a/guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java
+++ b/guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java
@@ -111,120 +111,6 @@ public class GuavaCollectionTypesUnitTest {
assertThat(immutable, contains("John", "Adam", "Jane", "Tom"));
}
- // sets
-
- @Test
- public void whenCalculateUnionOfSets_thenCorrect() {
- final Set first = ImmutableSet.of('a', 'b', 'c');
- final Set second = ImmutableSet.of('b', 'c', 'd');
-
- final Set union = Sets.union(first, second);
- assertThat(union, containsInAnyOrder('a', 'b', 'c', 'd'));
- }
-
- @Test
- public void whenCalculateSetsProduct_thenCorrect() {
- final Set first = ImmutableSet.of('a', 'b');
- final Set second = ImmutableSet.of('c', 'd');
- final Set> result = Sets.cartesianProduct(ImmutableList.of(first, second));
-
- final Function, String> func = new Function, String>() {
- @Override
- public final String apply(final List input) {
- return Joiner.on(" ").join(input);
- }
- };
-
- final Iterable joined = Iterables.transform(result, func);
- assertThat(joined, containsInAnyOrder("a c", "a d", "b c", "b d"));
- }
-
- @Test
- public void whenCalculatingSetIntersection_thenCorrect() {
- final Set first = ImmutableSet.of('a', 'b', 'c');
- final Set second = ImmutableSet.of('b', 'c', 'd');
-
- final Set intersection = Sets.intersection(first, second);
- assertThat(intersection, containsInAnyOrder('b', 'c'));
- }
-
- @Test
- public void whenCalculatingSetSymmetricDifference_thenCorrect() {
- final Set first = ImmutableSet.of('a', 'b', 'c');
- final Set second = ImmutableSet.of('b', 'c', 'd');
-
- final Set intersection = Sets.symmetricDifference(first, second);
- assertThat(intersection, containsInAnyOrder('a', 'd'));
- }
-
- @Test
- public void whenCalculatingPowerSet_thenCorrect() {
- final Set chars = ImmutableSet.of('a', 'b');
- final Set> result = Sets.powerSet(chars);
-
- final Set empty = ImmutableSet. builder().build();
- final Set a = ImmutableSet.of('a');
- final Set b = ImmutableSet.of('b');
- final Set aB = ImmutableSet.of('a', 'b');
-
- assertThat(result, contains(empty, a, b, aB));
- }
-
- @Test
- public void whenCreateRangeOfIntegersSet_thenCreated() {
- final int start = 10;
- final int end = 30;
- final ContiguousSet set = ContiguousSet.create(Range.closed(start, end), DiscreteDomain.integers());
-
- assertEquals(21, set.size());
- assertEquals(10, set.first().intValue());
- assertEquals(30, set.last().intValue());
- }
-
- @Test
- public void whenCreateRangeSet_thenCreated() {
- final RangeSet rangeSet = TreeRangeSet.create();
- rangeSet.add(Range.closed(1, 10));
- rangeSet.add(Range.closed(12, 15));
-
- assertEquals(2, rangeSet.asRanges().size());
-
- rangeSet.add(Range.closed(10, 12));
- assertTrue(rangeSet.encloses(Range.closed(1, 15)));
- assertEquals(1, rangeSet.asRanges().size());
- }
-
- @Test
- public void whenInsertDuplicatesInMultiSet_thenInserted() {
- final Multiset names = HashMultiset.create();
- names.add("John");
- names.add("Adam", 3);
- names.add("John");
-
- assertEquals(2, names.count("John"));
- names.remove("John");
- assertEquals(1, names.count("John"));
-
- assertEquals(3, names.count("Adam"));
- names.remove("Adam", 2);
- assertEquals(1, names.count("Adam"));
- }
-
- @Test
- public void whenGetTopUsingMultiSet_thenCorrect() {
- final Multiset names = HashMultiset.create();
- names.add("John");
- names.add("Adam", 5);
- names.add("Jane");
- names.add("Tom", 2);
-
- final Set sorted = Multisets.copyHighestCountFirst(names).elementSet();
- final List topTwo = Lists.newArrayList(sorted).subList(0, 2);
- assertEquals(2, topTwo.size());
- assertEquals("Adam", topTwo.get(0));
- assertEquals("Tom", topTwo.get(1));
- }
-
@Test
public void whenCreateImmutableMap_thenCreated() {
final Map salary = ImmutableMap. builder().put("John", 1000).put("Jane", 1500).put("Adam", 2000).put("Tom", 2000).build();
diff --git a/jackson-2/README.md b/jackson-2/README.md
index 96ed960ac2..ee9f8458a0 100644
--- a/jackson-2/README.md
+++ b/jackson-2/README.md
@@ -7,4 +7,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field)
+- [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml)
- [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model)
+
diff --git a/java-collections-maps-2/README.md b/java-collections-maps-2/README.md
index 8bcafccfe8..ff84e93ce4 100644
--- a/java-collections-maps-2/README.md
+++ b/java-collections-maps-2/README.md
@@ -1,2 +1,3 @@
## Relevant Articles:
- [Map of Primitives in Java](https://www.baeldung.com/java-map-primitives)
+- [Copying a HashMap in Java](https://www.baeldung.com/java-copy-hashmap)
diff --git a/java-dates-2/README.md b/java-dates-2/README.md
index a6b5c8e574..35286115d4 100644
--- a/java-dates-2/README.md
+++ b/java-dates-2/README.md
@@ -1,2 +1,3 @@
## Relevant Articles:
- [Converting Between LocalDate and XMLGregorianCalendar](https://www.baeldung.com/java-localdate-to-xmlgregoriancalendar)
+- [Convert Time to Milliseconds in Java](https://www.baeldung.com/java-time-milliseconds)
diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD
new file mode 100644
index 0000000000..edda92221d
--- /dev/null
+++ b/java-strings-2/README.MD
@@ -0,0 +1,4 @@
+## Relevant Articles
+
+- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
+- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
diff --git a/java-strings-2/pom.xml b/java-strings-2/pom.xml
index 5279cf5777..9c27429139 100755
--- a/java-strings-2/pom.xml
+++ b/java-strings-2/pom.xml
@@ -15,28 +15,6 @@
-
- commons-io
- commons-io
- ${commons-io.version}
-
-
- log4j
- log4j
- ${log4j.version}
-
-
- commons-codec
- commons-codec
- ${commons-codec.version}
-
-
-
- org.assertj
- assertj-core
- ${assertj.version}
- test
-
org.openjdk.jmh
jmh-core
@@ -57,11 +35,6 @@
guava
${guava.version}
-
- com.vdurmont
- emoji-java
- ${emoji-java.version}
-
org.apache.commons
commons-lang3
@@ -73,38 +46,18 @@
${junit.version}
test
-
- org.junit.jupiter
- junit-jupiter-api
- ${junit-jupiter-api.version}
- test
-
-
org.hamcrest
hamcrest-library
${org.hamcrest.version}
test
-
-
-
- org.passay
- passay
- ${passay.version}
-
org.apache.commons
commons-text
${commons-text.version}
-
- org.ahocorasick
- ahocorasick
- ${ahocorasick.version}
-
-
@@ -131,18 +84,10 @@
-
3.8.1
- 1.10
-
- 3.6.1
61.1
27.0.1-jre
- 4.0.0
- 5.3.1
- 1.3.1
1.4
- 0.4.0
\ No newline at end of file
diff --git a/java-strings-2/src/main/java/com/baeldung/string/performance/RemovingStopwordsPerformanceComparison.java b/java-strings-2/src/main/java/com/baeldung/string/performance/RemovingStopwordsPerformanceComparison.java
new file mode 100644
index 0000000000..5b455459cd
--- /dev/null
+++ b/java-strings-2/src/main/java/com/baeldung/string/performance/RemovingStopwordsPerformanceComparison.java
@@ -0,0 +1,73 @@
+package com.baeldung.string.performance;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+
+
+@Fork(value = 3, warmups = 1)
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.MILLISECONDS)
+public class RemovingStopwordsPerformanceComparison {
+
+ private String data;
+
+ private List stopwords;
+
+ private String stopwordsRegex;
+
+
+ public static void main(String[] args) throws Exception {
+ org.openjdk.jmh.Main.main(args);
+ }
+
+ @Setup
+ public void setup() throws IOException {
+ data = new String(Files.readAllBytes(Paths.get("src/main/resources/shakespeare-hamlet.txt")));
+ data = data.toLowerCase();
+ stopwords = Files.readAllLines(Paths.get("src/main/resources/english_stopwords.txt"));
+ stopwordsRegex = stopwords.stream().collect(Collectors.joining("|", "\\b(", ")\\b\\s?"));
+ }
+
+ @Benchmark
+ public String removeManually() {
+ String[] allWords = data.split(" ");
+ StringBuilder builder = new StringBuilder();
+ for(String word:allWords) {
+ if(! stopwords.contains(word)) {
+ builder.append(word);
+ builder.append(' ');
+ }
+ }
+ return builder.toString().trim();
+ }
+
+ @Benchmark
+ public String removeAll() {
+ ArrayList allWords = Stream.of(data.split(" "))
+ .collect(Collectors.toCollection(ArrayList::new));
+ allWords.removeAll(stopwords);
+ return allWords.stream().collect(Collectors.joining(" "));
+ }
+
+ @Benchmark
+ public String replaceRegex() {
+ return data.replaceAll(stopwordsRegex, "");
+ }
+
+}
\ No newline at end of file
diff --git a/java-strings-2/src/main/resources/english_stopwords.txt b/java-strings-2/src/main/resources/english_stopwords.txt
new file mode 100644
index 0000000000..5b16b504d6
--- /dev/null
+++ b/java-strings-2/src/main/resources/english_stopwords.txt
@@ -0,0 +1,127 @@
+i
+me
+my
+myself
+we
+our
+ours
+ourselves
+you
+your
+yours
+yourself
+yourselves
+he
+him
+his
+himself
+she
+her
+hers
+herself
+it
+its
+itself
+they
+them
+their
+theirs
+themselves
+what
+which
+who
+whom
+this
+that
+these
+those
+am
+is
+are
+was
+were
+be
+been
+being
+have
+has
+had
+having
+do
+does
+did
+doing
+a
+an
+the
+and
+but
+if
+or
+because
+as
+until
+while
+of
+at
+by
+for
+with
+about
+against
+between
+into
+through
+during
+before
+after
+above
+below
+to
+from
+up
+down
+in
+out
+on
+off
+over
+under
+again
+further
+then
+once
+here
+there
+when
+where
+why
+how
+all
+any
+both
+each
+few
+more
+most
+other
+some
+such
+no
+nor
+not
+only
+own
+same
+so
+than
+too
+very
+s
+t
+can
+will
+just
+don
+should
+now
diff --git a/java-strings-2/src/main/resources/shakespeare-hamlet.txt b/java-strings-2/src/main/resources/shakespeare-hamlet.txt
new file mode 100644
index 0000000000..0156555388
--- /dev/null
+++ b/java-strings-2/src/main/resources/shakespeare-hamlet.txt
@@ -0,0 +1,4922 @@
+[The Tragedie of Hamlet by William Shakespeare 1599]
+
+
+Actus Primus. Scoena Prima.
+
+Enter Barnardo and Francisco two Centinels.
+
+ Barnardo. Who's there?
+ Fran. Nay answer me: Stand & vnfold
+your selfe
+
+ Bar. Long liue the King
+
+ Fran. Barnardo?
+ Bar. He
+
+ Fran. You come most carefully vpon your houre
+
+ Bar. 'Tis now strook twelue, get thee to bed Francisco
+
+ Fran. For this releefe much thankes: 'Tis bitter cold,
+And I am sicke at heart
+
+ Barn. Haue you had quiet Guard?
+ Fran. Not a Mouse stirring
+
+ Barn. Well, goodnight. If you do meet Horatio and
+Marcellus, the Riuals of my Watch, bid them make hast.
+Enter Horatio and Marcellus.
+
+ Fran. I thinke I heare them. Stand: who's there?
+ Hor. Friends to this ground
+
+ Mar. And Leige-men to the Dane
+
+ Fran. Giue you good night
+
+ Mar. O farwel honest Soldier, who hath relieu'd you?
+ Fra. Barnardo ha's my place: giue you goodnight.
+
+Exit Fran.
+
+ Mar. Holla Barnardo
+
+ Bar. Say, what is Horatio there?
+ Hor. A peece of him
+
+ Bar. Welcome Horatio, welcome good Marcellus
+
+ Mar. What, ha's this thing appear'd againe to night
+
+ Bar. I haue seene nothing
+
+ Mar. Horatio saies, 'tis but our Fantasie,
+And will not let beleefe take hold of him
+Touching this dreaded sight, twice seene of vs,
+Therefore I haue intreated him along
+With vs, to watch the minutes of this Night,
+That if againe this Apparition come,
+He may approue our eyes, and speake to it
+
+ Hor. Tush, tush, 'twill not appeare
+
+ Bar. Sit downe a-while,
+And let vs once againe assaile your eares,
+That are so fortified against our Story,
+What we two Nights haue seene
+
+ Hor. Well, sit we downe,
+And let vs heare Barnardo speake of this
+
+ Barn. Last night of all,
+When yond same Starre that's Westward from the Pole
+Had made his course t' illume that part of Heauen
+Where now it burnes, Marcellus and my selfe,
+The Bell then beating one
+
+ Mar. Peace, breake thee of:
+Enter the Ghost.
+
+Looke where it comes againe
+
+ Barn. In the same figure, like the King that's dead
+
+ Mar. Thou art a Scholler; speake to it Horatio
+
+ Barn. Lookes it not like the King? Marke it Horatio
+
+ Hora. Most like: It harrowes me with fear & wonder
+ Barn. It would be spoke too
+
+ Mar. Question it Horatio
+
+ Hor. What art thou that vsurp'st this time of night,
+Together with that Faire and Warlike forme
+In which the Maiesty of buried Denmarke
+Did sometimes march: By Heauen I charge thee speake
+
+ Mar. It is offended
+
+ Barn. See, it stalkes away
+
+ Hor. Stay: speake; speake: I Charge thee, speake.
+
+Exit the Ghost.
+
+ Mar. 'Tis gone, and will not answer
+
+ Barn. How now Horatio? You tremble & look pale:
+Is not this something more then Fantasie?
+What thinke you on't?
+ Hor. Before my God, I might not this beleeue
+Without the sensible and true auouch
+Of mine owne eyes
+
+ Mar. Is it not like the King?
+ Hor. As thou art to thy selfe,
+Such was the very Armour he had on,
+When th' Ambitious Norwey combatted:
+So frown'd he once, when in an angry parle
+He smot the sledded Pollax on the Ice.
+'Tis strange
+
+ Mar. Thus twice before, and iust at this dead houre,
+With Martiall stalke, hath he gone by our Watch
+
+ Hor. In what particular thought to work, I know not:
+But in the grosse and scope of my Opinion,
+This boades some strange erruption to our State
+
+ Mar. Good now sit downe, & tell me he that knowes
+Why this same strict and most obseruant Watch,
+So nightly toyles the subiect of the Land,
+And why such dayly Cast of Brazon Cannon
+And Forraigne Mart for Implements of warre:
+Why such impresse of Ship-wrights, whose sore Taske
+Do's not diuide the Sunday from the weeke,
+What might be toward, that this sweaty hast
+Doth make the Night ioynt-Labourer with the day:
+Who is't that can informe me?
+ Hor. That can I,
+At least the whisper goes so: Our last King,
+Whose Image euen but now appear'd to vs,
+Was (as you know) by Fortinbras of Norway,
+(Thereto prick'd on by a most emulate Pride)
+Dar'd to the Combate. In which, our Valiant Hamlet,
+(For so this side of our knowne world esteem'd him)
+Did slay this Fortinbras: who by a Seal'd Compact,
+Well ratified by Law, and Heraldrie,
+Did forfeite (with his life) all those his Lands
+Which he stood seiz'd on, to the Conqueror:
+Against the which, a Moity competent
+Was gaged by our King: which had return'd
+To the Inheritance of Fortinbras,
+Had he bin Vanquisher, as by the same Cou'nant
+And carriage of the Article designe,
+His fell to Hamlet. Now sir, young Fortinbras,
+Of vnimproued Mettle, hot and full,
+Hath in the skirts of Norway, heere and there,
+Shark'd vp a List of Landlesse Resolutes,
+For Foode and Diet, to some Enterprize
+That hath a stomacke in't: which is no other
+(And it doth well appeare vnto our State)
+But to recouer of vs by strong hand
+And termes Compulsatiue, those foresaid Lands
+So by his Father lost: and this (I take it)
+Is the maine Motiue of our Preparations,
+The Sourse of this our Watch, and the cheefe head
+Of this post-hast, and Romage in the Land.
+Enter Ghost againe.
+
+But soft, behold: Loe, where it comes againe:
+Ile crosse it, though it blast me. Stay Illusion:
+If thou hast any sound, or vse of Voyce,
+Speake to me. If there be any good thing to be done,
+That may to thee do ease, and grace to me; speak to me.
+If thou art priuy to thy Countries Fate
+(Which happily foreknowing may auoyd) Oh speake.
+Or, if thou hast vp-hoorded in thy life
+Extorted Treasure in the wombe of Earth,
+(For which, they say, you Spirits oft walke in death)
+Speake of it. Stay, and speake. Stop it Marcellus
+
+ Mar. Shall I strike at it with my Partizan?
+ Hor. Do, if it will not stand
+
+ Barn. 'Tis heere
+
+ Hor. 'Tis heere
+
+ Mar. 'Tis gone.
+
+Exit Ghost.
+
+We do it wrong, being so Maiesticall
+To offer it the shew of Violence,
+For it is as the Ayre, invulnerable,
+And our vaine blowes, malicious Mockery
+
+ Barn. It was about to speake, when the Cocke crew
+
+ Hor. And then it started, like a guilty thing
+Vpon a fearfull Summons. I haue heard,
+The Cocke that is the Trumpet to the day,
+Doth with his lofty and shrill-sounding Throate
+Awake the God of Day: and at his warning,
+Whether in Sea, or Fire, in Earth, or Ayre,
+Th' extrauagant, and erring Spirit, hyes
+To his Confine. And of the truth heerein,
+This present Obiect made probation
+
+ Mar. It faded on the crowing of the Cocke.
+Some sayes, that euer 'gainst that Season comes
+Wherein our Sauiours Birch is celebrated,
+The Bird of Dawning singeth all night long:
+And then (they say) no Spirit can walke abroad,
+The nights are wholsome, then no Planets strike,
+No Faiery talkes, nor Witch hath power to Charme:
+So hallow'd, and so gracious is the time
+
+ Hor. So haue I heard, and do in part beleeue it.
+But looke, the Morne in Russet mantle clad,
+Walkes o're the dew of yon high Easterne Hill,
+Breake we our Watch vp, and by my aduice
+Let vs impart what we haue seene to night
+Vnto yong Hamlet. For vpon my life,
+This Spirit dumbe to vs, will speake to him:
+Do you consent we shall acquaint him with it,
+As needfull in our Loues, fitting our Duty?
+ Mar. Let do't I pray, and I this morning know
+Where we shall finde him most conueniently.
+
+Exeunt.
+
+Scena Secunda.
+
+Enter Claudius King of Denmarke, Gertrude the Queene, Hamlet,
+Polonius,
+Laertes, and his Sister Ophelia, Lords Attendant.
+
+ King. Though yet of Hamlet our deere Brothers death
+The memory be greene: and that it vs befitted
+To beare our hearts in greefe, and our whole Kingdome
+To be contracted in one brow of woe:
+Yet so farre hath Discretion fought with Nature,
+That we with wisest sorrow thinke on him,
+Together with remembrance of our selues.
+Therefore our sometimes Sister, now our Queene,
+Th' imperiall Ioyntresse of this warlike State,
+Haue we, as 'twere, with a defeated ioy,
+With one Auspicious, and one Dropping eye,
+With mirth in Funerall, and with Dirge in Marriage,
+In equall Scale weighing Delight and Dole
+Taken to Wife; nor haue we heerein barr'd
+Your better Wisedomes, which haue freely gone
+With this affaire along, for all our Thankes.
+Now followes, that you know young Fortinbras,
+Holding a weake supposall of our worth;
+Or thinking by our late deere Brothers death,
+Our State to be disioynt, and out of Frame,
+Colleagued with the dreame of his Aduantage;
+He hath not fayl'd to pester vs with Message,
+Importing the surrender of those Lands
+Lost by his Father: with all Bonds of Law
+To our most valiant Brother. So much for him.
+Enter Voltemand and Cornelius.
+
+Now for our selfe, and for this time of meeting
+Thus much the businesse is. We haue heere writ
+To Norway, Vncle of young Fortinbras,
+Who Impotent and Bedrid, scarsely heares
+Of this his Nephewes purpose, to suppresse
+His further gate heerein. In that the Leuies,
+The Lists, and full proportions are all made
+Out of his subiect: and we heere dispatch
+You good Cornelius, and you Voltemand,
+For bearing of this greeting to old Norway,
+Giuing to you no further personall power
+To businesse with the King, more then the scope
+Of these dilated Articles allow:
+Farewell, and let your hast commend your duty
+
+ Volt. In that, and all things, will we shew our duty
+
+ King. We doubt it nothing, heartily farewell.
+
+Exit Voltemand and Cornelius.
+
+And now Laertes, what's the newes with you?
+You told vs of some suite. What is't Laertes?
+You cannot speake of Reason to the Dane,
+And loose your voyce. What would'st thou beg Laertes,
+That shall not be my Offer, not thy Asking?
+The Head is not more Natiue to the Heart,
+The Hand more instrumentall to the Mouth,
+Then is the Throne of Denmarke to thy Father.
+What would'st thou haue Laertes?
+ Laer. Dread my Lord,
+Your leaue and fauour to returne to France,
+From whence, though willingly I came to Denmarke
+To shew my duty in your Coronation,
+Yet now I must confesse, that duty done,
+My thoughts and wishes bend againe towards France,
+And bow them to your gracious leaue and pardon
+
+ King. Haue you your Fathers leaue?
+What sayes Pollonius?
+ Pol. He hath my Lord:
+I do beseech you giue him leaue to go
+
+ King. Take thy faire houre Laertes, time be thine,
+And thy best graces spend it at thy will:
+But now my Cosin Hamlet, and my Sonne?
+ Ham. A little more then kin, and lesse then kinde
+
+ King. How is it that the Clouds still hang on you?
+ Ham. Not so my Lord, I am too much i'th' Sun
+
+ Queen. Good Hamlet cast thy nightly colour off,
+And let thine eye looke like a Friend on Denmarke.
+Do not for euer with thy veyled lids
+Seeke for thy Noble Father in the dust;
+Thou know'st 'tis common, all that liues must dye,
+Passing through Nature, to Eternity
+
+ Ham. I Madam, it is common
+
+ Queen. If it be;
+Why seemes it so particular with thee
+
+ Ham. Seemes Madam? Nay, it is: I know not Seemes:
+'Tis not alone my Inky Cloake (good Mother)
+Nor Customary suites of solemne Blacke,
+Nor windy suspiration of forc'd breath,
+No, nor the fruitfull Riuer in the Eye,
+Nor the deiected hauiour of the Visage,
+Together with all Formes, Moods, shewes of Griefe,
+That can denote me truly. These indeed Seeme,
+For they are actions that a man might play:
+But I haue that Within, which passeth show;
+These, but the Trappings, and the Suites of woe
+
+ King. 'Tis sweet and commendable
+In your Nature Hamlet,
+To giue these mourning duties to your Father:
+But you must know, your Father lost a Father,
+That Father lost, lost his, and the Suruiuer bound
+In filiall Obligation, for some terme
+To do obsequious Sorrow. But to perseuer
+In obstinate Condolement, is a course
+Of impious stubbornnesse. 'Tis vnmanly greefe,
+It shewes a will most incorrect to Heauen,
+A Heart vnfortified, a Minde impatient,
+An Vnderstanding simple, and vnschool'd:
+For, what we know must be, and is as common
+As any the most vulgar thing to sence,
+Why should we in our peeuish Opposition
+Take it to heart? Fye, 'tis a fault to Heauen,
+A fault against the Dead, a fault to Nature,
+To Reason most absurd, whose common Theame
+Is death of Fathers, and who still hath cried,
+From the first Coarse, till he that dyed to day,
+This must be so. We pray you throw to earth
+This vnpreuayling woe, and thinke of vs
+As of a Father; For let the world take note,
+You are the most immediate to our Throne,
+And with no lesse Nobility of Loue,
+Then that which deerest Father beares his Sonne,
+Do I impart towards you. For your intent
+In going backe to Schoole in Wittenberg,
+It is most retrograde to our desire:
+And we beseech you, bend you to remaine
+Heere in the cheere and comfort of our eye,
+Our cheefest Courtier Cosin, and our Sonne
+
+ Qu. Let not thy Mother lose her Prayers Hamlet:
+I prythee stay with vs, go not to Wittenberg
+
+ Ham. I shall in all my best
+Obey you Madam
+
+ King. Why 'tis a louing, and a faire Reply,
+Be as our selfe in Denmarke. Madam come,
+This gentle and vnforc'd accord of Hamlet
+Sits smiling to my heart; in grace whereof,
+No iocond health that Denmarke drinkes to day,
+But the great Cannon to the Clowds shall tell,
+And the Kings Rouce, the Heauens shall bruite againe,
+Respeaking earthly Thunder. Come away.
+
+Exeunt.
+
+Manet Hamlet.
+
+ Ham. Oh that this too too solid Flesh, would melt,
+Thaw, and resolue it selfe into a Dew:
+Or that the Euerlasting had not fixt
+His Cannon 'gainst Selfe-slaughter. O God, O God!
+How weary, stale, flat, and vnprofitable
+Seemes to me all the vses of this world?
+Fie on't? Oh fie, fie, 'tis an vnweeded Garden
+That growes to Seed: Things rank, and grosse in Nature
+Possesse it meerely. That it should come to this:
+But two months dead: Nay, not so much; not two,
+So excellent a King, that was to this
+Hiperion to a Satyre: so louing to my Mother,
+That he might not beteene the windes of heauen
+Visit her face too roughly. Heauen and Earth
+Must I remember: why she would hang on him,
+As if encrease of Appetite had growne
+By what is fed on; and yet within a month?
+Let me not thinke on't: Frailty, thy name is woman.
+A little Month, or ere those shooes were old,
+With which she followed my poore Fathers body
+Like Niobe, all teares. Why she, euen she.
+(O Heauen! A beast that wants discourse of Reason
+Would haue mourn'd longer) married with mine Vnkle,
+My Fathers Brother: but no more like my Father,
+Then I to Hercules. Within a Moneth?
+Ere yet the salt of most vnrighteous Teares
+Had left the flushing of her gauled eyes,
+She married. O most wicked speed, to post
+With such dexterity to Incestuous sheets:
+It is not, nor it cannot come to good.
+But breake my heart, for I must hold my tongue.
+Enter Horatio, Barnardo, and Marcellus.
+
+ Hor. Haile to your Lordship
+
+ Ham. I am glad to see you well:
+Horatio, or I do forget my selfe
+
+ Hor. The same my Lord,
+And your poore Seruant euer
+
+ Ham. Sir my good friend,
+Ile change that name with you:
+And what make you from Wittenberg Horatio?
+Marcellus
+
+ Mar. My good Lord
+
+ Ham. I am very glad to see you: good euen Sir.
+But what in faith make you from Wittemberge?
+ Hor. A truant disposition, good my Lord
+
+ Ham. I would not haue your Enemy say so;
+Nor shall you doe mine eare that violence,
+To make it truster of your owne report
+Against your selfe. I know you are no Truant:
+But what is your affaire in Elsenour?
+Wee'l teach you to drinke deepe, ere you depart
+
+ Hor. My Lord, I came to see your Fathers Funerall
+
+ Ham. I pray thee doe not mock me (fellow Student)
+I thinke it was to see my Mothers Wedding
+
+ Hor. Indeed my Lord, it followed hard vpon
+
+ Ham. Thrift thrift Horatio: the Funerall Bakt-meats
+Did coldly furnish forth the Marriage Tables;
+Would I had met my dearest foe in heauen,
+Ere I had euer seene that day Horatio.
+My father, me thinkes I see my father
+
+ Hor. Oh where my Lord?
+ Ham. In my minds eye (Horatio)
+ Hor. I saw him once; he was a goodly King
+
+ Ham. He was a man, take him for all in all:
+I shall not look vpon his like againe
+
+ Hor. My Lord, I thinke I saw him yesternight
+
+ Ham. Saw? Who?
+ Hor. My Lord, the King your Father
+
+ Ham. The King my Father?
+ Hor. Season your admiration for a while
+With an attent eare; till I may deliuer
+Vpon the witnesse of these Gentlemen,
+This maruell to you
+
+ Ham. For Heauens loue let me heare
+
+ Hor. Two nights together, had these Gentlemen
+(Marcellus and Barnardo) on their Watch
+In the dead wast and middle of the night
+Beene thus encountred. A figure like your Father,
+Arm'd at all points exactly, Cap a Pe,
+Appeares before them, and with sollemne march
+Goes slow and stately: By them thrice he walkt,
+By their opprest and feare-surprized eyes,
+Within his Truncheons length; whilst they bestil'd
+Almost to Ielly with the Act of feare,
+Stand dumbe and speake not to him. This to me
+In dreadfull secrecie impart they did,
+And I with them the third Night kept the Watch,
+Whereas they had deliuer'd both in time,
+Forme of the thing; each word made true and good,
+The Apparition comes. I knew your Father:
+These hands are not more like
+
+ Ham. But where was this?
+ Mar. My Lord vpon the platforme where we watcht
+
+ Ham. Did you not speake to it?
+ Hor. My Lord, I did;
+But answere made it none: yet once me thought
+It lifted vp it head, and did addresse
+It selfe to motion, like as it would speake:
+But euen then, the Morning Cocke crew lowd;
+And at the sound it shrunke in hast away,
+And vanisht from our sight
+
+ Ham. Tis very strange
+
+ Hor. As I doe liue my honourd Lord 'tis true;
+And we did thinke it writ downe in our duty
+To let you know of it
+
+ Ham. Indeed, indeed Sirs; but this troubles me.
+Hold you the watch to Night?
+ Both. We doe my Lord
+
+ Ham. Arm'd, say you?
+ Both. Arm'd, my Lord
+
+ Ham. From top to toe?
+ Both. My Lord, from head to foote
+
+ Ham. Then saw you not his face?
+ Hor. O yes, my Lord, he wore his Beauer vp
+
+ Ham. What, lookt he frowningly?
+ Hor. A countenance more in sorrow then in anger
+
+ Ham. Pale, or red?
+ Hor. Nay very pale
+
+ Ham. And fixt his eyes vpon you?
+ Hor. Most constantly
+
+ Ham. I would I had beene there
+
+ Hor. It would haue much amaz'd you
+
+ Ham. Very like, very like: staid it long?
+ Hor. While one with moderate hast might tell a hundred
+
+ All. Longer, longer
+
+ Hor. Not when I saw't
+
+ Ham. His Beard was grisly? no
+
+ Hor. It was, as I haue seene it in his life,
+A Sable Siluer'd
+
+ Ham. Ile watch to Night; perchance 'twill wake againe
+
+ Hor. I warrant you it will
+
+ Ham. If it assume my noble Fathers person,
+Ile speake to it, though Hell it selfe should gape
+And bid me hold my peace. I pray you all,
+If you haue hitherto conceald this sight;
+Let it bee treble in your silence still:
+And whatsoeuer els shall hap to night,
+Giue it an vnderstanding but no tongue;
+I will requite your loues; so fare ye well:
+Vpon the Platforme twixt eleuen and twelue,
+Ile visit you
+
+ All. Our duty to your Honour.
+
+Exeunt
+
+ Ham. Your loue, as mine to you: farewell.
+My Fathers Spirit in Armes? All is not well:
+I doubt some foule play: would the Night were come;
+Till then sit still my soule; foule deeds will rise,
+Though all the earth orewhelm them to mens eies.
+Enter.
+
+
+Scena Tertia
+
+
+Enter Laertes and Ophelia.
+
+ Laer. My necessaries are imbark't; Farewell:
+And Sister, as the Winds giue Benefit,
+And Conuoy is assistant; doe not sleepe,
+But let me heare from you
+
+ Ophel. Doe you doubt that?
+ Laer. For Hamlet, and the trifling of his fauours,
+Hold it a fashion and a toy in Bloude;
+A Violet in the youth of Primy Nature;
+Froward, not permanent; sweet not lasting
+The suppliance of a minute? No more
+
+ Ophel. No more but so
+
+ Laer. Thinke it no more:
+For nature cressant does not grow alone,
+In thewes and Bulke: but as his Temple waxes,
+The inward seruice of the Minde and Soule
+Growes wide withall. Perhaps he loues you now,
+And now no soyle nor cautell doth besmerch
+The vertue of his feare: but you must feare
+His greatnesse weigh'd, his will is not his owne;
+For hee himselfe is subiect to his Birth:
+Hee may not, as vnuallued persons doe,
+Carue for himselfe; for, on his choyce depends
+The sanctity and health of the whole State.
+And therefore must his choyce be circumscrib'd
+Vnto the voyce and yeelding of that Body,
+Whereof he is the Head. Then if he sayes he loues you,
+It fits your wisedome so farre to beleeue it;
+As he in his peculiar Sect and force
+May giue his saying deed: which is no further,
+Then the maine voyce of Denmarke goes withall.
+Then weight what losse your Honour may sustaine,
+If with too credent eare you list his Songs;
+Or lose your Heart; or your chast Treasure open
+To his vnmastred importunity.
+Feare it Ophelia, feare it my deare Sister,
+And keepe within the reare of your Affection;
+Out of the shot and danger of Desire.
+The chariest Maid is Prodigall enough,
+If she vnmaske her beauty to the Moone:
+Vertue it selfe scapes not calumnious stroakes,
+The Canker Galls, the Infants of the Spring
+Too oft before the buttons be disclos'd,
+And in the Morne and liquid dew of Youth,
+Contagious blastments are most imminent.
+Be wary then, best safety lies in feare;
+Youth to it selfe rebels, though none else neere
+
+ Ophe. I shall th' effect of this good Lesson keepe,
+As watchmen to my heart: but good my Brother
+Doe not as some vngracious Pastors doe,
+Shew me the steepe and thorny way to Heauen;
+Whilst like a puft and recklesse Libertine
+Himselfe, the Primrose path of dalliance treads,
+And reaks not his owne reade
+
+ Laer. Oh, feare me not.
+Enter Polonius.
+
+I stay too long; but here my Father comes:
+A double blessing is a double grace;
+Occasion smiles vpon a second leaue
+
+ Polon. Yet heere Laertes? Aboord, aboord for shame,
+The winde sits in the shoulder of your saile,
+And you are staid for there: my blessing with you;
+And these few Precepts in thy memory,
+See thou Character. Giue thy thoughts no tongue,
+Nor any vnproportion'd thoughts his Act:
+Be thou familiar; but by no meanes vulgar:
+The friends thou hast, and their adoption tride,
+Grapple them to thy Soule, with hoopes of Steele:
+But doe not dull thy palme, with entertainment
+Of each vnhatch't, vnfledg'd Comrade. Beware
+Of entrance to a quarrell: but being in
+Bear't that th' opposed may beware of thee.
+Giue euery man thine eare; but few thy voyce:
+Take each mans censure; but reserue thy iudgement:
+Costly thy habit as thy purse can buy;
+But not exprest in fancie; rich, not gawdie:
+For the Apparell oft proclaimes the man.
+And they in France of the best ranck and station,
+Are of a most select and generous cheff in that.
+Neither a borrower, nor a lender be;
+For lone oft loses both it selfe and friend:
+And borrowing duls the edge of Husbandry.
+This aboue all; to thine owne selfe be true:
+And it must follow, as the Night the Day,
+Thou canst not then be false to any man.
+Farewell: my Blessing season this in thee
+
+ Laer. Most humbly doe I take my leaue, my Lord
+
+ Polon. The time inuites you, goe, your seruants tend
+
+ Laer. Farewell Ophelia, and remember well
+What I haue said to you
+
+ Ophe. Tis in my memory lockt,
+And you your selfe shall keepe the key of it
+
+ Laer. Farewell.
+
+Exit Laer.
+
+ Polon. What ist Ophelia he hath said to you?
+ Ophe. So please you, somthing touching the L[ord]. Hamlet
+
+ Polon. Marry, well bethought:
+Tis told me he hath very oft of late
+Giuen priuate time to you; and you your selfe
+Haue of your audience beene most free and bounteous.
+If it be so, as so tis put on me;
+And that in way of caution: I must tell you,
+You doe not vnderstand your selfe so cleerely,
+As it behoues my Daughter, and your Honour.
+What is betweene you, giue me vp the truth?
+ Ophe. He hath my Lord of late, made many tenders
+Of his affection to me
+
+ Polon. Affection, puh. You speake like a greene Girle,
+Vnsifted in such perillous Circumstance.
+Doe you beleeue his tenders, as you call them?
+ Ophe. I do not know, my Lord, what I should thinke
+
+ Polon. Marry Ile teach you; thinke your selfe a Baby,
+That you haue tane his tenders for true pay,
+Which are not starling. Tender your selfe more dearly;
+Or not to crack the winde of the poore Phrase,
+Roaming it thus, you'l tender me a foole
+
+ Ophe. My Lord, he hath importun'd me with loue,
+In honourable fashion
+
+ Polon. I, fashion you may call it, go too, go too
+
+ Ophe. And hath giuen countenance to his speech,
+My Lord, with all the vowes of Heauen
+
+ Polon. I, Springes to catch Woodcocks. I doe know
+When the Bloud burnes, how Prodigall the Soule
+Giues the tongue vowes: these blazes, Daughter,
+Giuing more light then heate; extinct in both,
+Euen in their promise, as it is a making;
+You must not take for fire. For this time Daughter,
+Be somewhat scanter of your Maiden presence;
+Set your entreatments at a higher rate,
+Then a command to parley. For Lord Hamlet,
+Beleeue so much in him, that he is young,
+And with a larger tether may he walke,
+Then may be giuen you. In few, Ophelia,
+Doe not beleeue his vowes; for they are Broakers,
+Not of the eye, which their Inuestments show:
+But meere implorators of vnholy Sutes,
+Breathing like sanctified and pious bonds,
+The better to beguile. This is for all:
+I would not, in plaine tearmes, from this time forth,
+Haue you so slander any moment leisure,
+As to giue words or talke with the Lord Hamlet:
+Looke too't, I charge you; come your wayes
+
+ Ophe. I shall obey my Lord.
+
+Exeunt.
+
+Enter Hamlet, Horatio, Marcellus.
+
+ Ham. The Ayre bites shrewdly: is it very cold?
+ Hor. It is a nipping and an eager ayre
+
+ Ham. What hower now?
+ Hor. I thinke it lacks of twelue
+
+ Mar. No, it is strooke
+
+ Hor. Indeed I heard it not: then it drawes neere the season,
+Wherein the Spirit held his wont to walke.
+What does this meane my Lord?
+ Ham. The King doth wake to night, and takes his rouse,
+Keepes wassels and the swaggering vpspring reeles,
+And as he dreines his draughts of Renish downe,
+The kettle Drum and Trumpet thus bray out
+The triumph of his Pledge
+
+ Horat. Is it a custome?
+ Ham. I marry ist;
+And to my mind, though I am natiue heere,
+And to the manner borne: It is a Custome
+More honour'd in the breach, then the obseruance.
+Enter Ghost.
+
+ Hor. Looke my Lord, it comes
+
+ Ham. Angels and Ministers of Grace defend vs:
+Be thou a Spirit of health, or Goblin damn'd,
+Bring with thee ayres from Heauen, or blasts from Hell,
+Be thy euents wicked or charitable,
+Thou com'st in such a questionable shape
+That I will speake to thee. Ile call thee Hamlet,
+King, Father, Royall Dane: Oh, oh, answer me,
+Let me not burst in Ignorance; but tell
+Why thy Canoniz'd bones Hearsed in death,
+Haue burst their cerments, why the Sepulcher
+Wherein we saw thee quietly enurn'd,
+Hath op'd his ponderous and Marble iawes,
+To cast thee vp againe? What may this meane?
+That thou dead Coarse againe in compleat steele,
+Reuisits thus the glimpses of the Moone,
+Making Night hidious? And we fooles of Nature,
+So horridly to shake our disposition,
+With thoughts beyond thee; reaches of our Soules,
+Say, why is this? wherefore? what should we doe?
+
+Ghost beckens Hamlet.
+
+ Hor. It beckons you to goe away with it,
+As if it some impartment did desire
+To you alone
+
+ Mar. Looke with what courteous action
+It wafts you to a more remoued ground:
+But doe not goe with it
+
+ Hor. No, by no meanes
+
+ Ham. It will not speake: then will I follow it
+
+ Hor. Doe not my Lord
+
+ Ham. Why, what should be the feare?
+I doe not set my life at a pins fee;
+And for my Soule, what can it doe to that?
+Being a thing immortall as it selfe:
+It waues me forth againe; Ile follow it
+
+ Hor. What if it tempt you toward the Floud my Lord?
+Or to the dreadfull Sonnet of the Cliffe,
+That beetles o're his base into the Sea,
+And there assumes some other horrible forme,
+Which might depriue your Soueraignty of Reason,
+And draw you into madnesse thinke of it?
+ Ham. It wafts me still: goe on, Ile follow thee
+
+ Mar. You shall not goe my Lord
+
+ Ham. Hold off your hand
+
+ Hor. Be rul'd, you shall not goe
+
+ Ham. My fate cries out,
+And makes each petty Artire in this body,
+As hardy as the Nemian Lions nerue:
+Still am I cal'd? Vnhand me Gentlemen:
+By Heau'n, Ile make a Ghost of him that lets me:
+I say away, goe on, Ile follow thee.
+
+Exeunt. Ghost & Hamlet.
+
+ Hor. He waxes desperate with imagination
+
+ Mar. Let's follow; 'tis not fit thus to obey him
+
+ Hor. Haue after, to what issue will this come?
+ Mar. Something is rotten in the State of Denmarke
+
+ Hor. Heauen will direct it
+
+ Mar. Nay, let's follow him.
+
+Exeunt.
+
+Enter Ghost and Hamlet.
+
+ Ham. Where wilt thou lead me? speak; Ile go no further
+
+ Gho. Marke me
+
+ Ham. I will
+
+ Gho. My hower is almost come,
+When I to sulphurous and tormenting Flames
+Must render vp my selfe
+
+ Ham. Alas poore Ghost
+
+ Gho. Pitty me not, but lend thy serious hearing
+To what I shall vnfold
+
+ Ham. Speake, I am bound to heare
+
+ Gho. So art thou to reuenge, when thou shalt heare
+
+ Ham. What?
+ Gho. I am thy Fathers Spirit,
+Doom'd for a certaine terme to walke the night;
+And for the day confin'd to fast in Fiers,
+Till the foule crimes done in my dayes of Nature
+Are burnt and purg'd away? But that I am forbid
+To tell the secrets of my Prison-House;
+I could a Tale vnfold, whose lightest word
+Would harrow vp thy soule, freeze thy young blood,
+Make thy two eyes like Starres, start from their Spheres,
+Thy knotty and combined lockes to part,
+And each particular haire to stand an end,
+Like Quilles vpon the fretfull Porpentine:
+But this eternall blason must not be
+To eares of flesh and bloud; list Hamlet, oh list,
+If thou didst euer thy deare Father loue
+
+ Ham. Oh Heauen!
+ Gho. Reuenge his foule and most vnnaturall Murther
+
+ Ham. Murther?
+ Ghost. Murther most foule, as in the best it is;
+But this most foule, strange, and vnnaturall
+
+ Ham. Hast, hast me to know it,
+That with wings as swift
+As meditation, or the thoughts of Loue,
+May sweepe to my Reuenge
+
+ Ghost. I finde thee apt,
+And duller should'st thou be then the fat weede
+That rots it selfe in ease, on Lethe Wharfe,
+Would'st thou not stirre in this. Now Hamlet heare:
+It's giuen out, that sleeping in mine Orchard,
+A Serpent stung me: so the whole eare of Denmarke,
+Is by a forged processe of my death
+Rankly abus'd: But know thou Noble youth,
+The Serpent that did sting thy Fathers life,
+Now weares his Crowne
+
+ Ham. O my Propheticke soule: mine Vncle?
+ Ghost. I that incestuous, that adulterate Beast
+With witchcraft of his wits, hath Traitorous guifts.
+Oh wicked Wit, and Gifts, that haue the power
+So to seduce? Won to this shamefull Lust
+The will of my most seeming vertuous Queene:
+Oh Hamlet, what a falling off was there,
+From me, whose loue was of that dignity,
+That it went hand in hand, euen with the Vow
+I made to her in Marriage; and to decline
+Vpon a wretch, whose Naturall gifts were poore
+To those of mine. But Vertue, as it neuer wil be moued,
+Though Lewdnesse court it in a shape of Heauen:
+So Lust, though to a radiant Angell link'd,
+Will sate it selfe in a Celestiall bed, & prey on Garbage.
+But soft, me thinkes I sent the Mornings Ayre;
+Briefe let me be: Sleeping within mine Orchard,
+My custome alwayes in the afternoone;
+Vpon my secure hower thy Vncle stole
+With iuyce of cursed Hebenon in a Violl,
+And in the Porches of mine eares did poure
+The leaperous Distilment; whose effect
+Holds such an enmity with bloud of Man,
+That swift as Quick-siluer, it courses through
+The naturall Gates and Allies of the body;
+And with a sodaine vigour it doth posset
+And curd, like Aygre droppings into Milke,
+The thin and wholsome blood: so did it mine;
+And a most instant Tetter bak'd about,
+Most Lazar-like, with vile and loathsome crust,
+All my smooth Body.
+Thus was I, sleeping, by a Brothers hand,
+Of Life, of Crowne, and Queene at once dispatcht;
+Cut off euen in the Blossomes of my Sinne,
+Vnhouzzled, disappointed, vnnaneld,
+No reckoning made, but sent to my account
+With all my imperfections on my head;
+Oh horrible Oh horrible, most horrible:
+If thou hast nature in thee beare it not;
+Let not the Royall Bed of Denmarke be
+A Couch for Luxury and damned Incest.
+But howsoeuer thou pursuest this Act,
+Taint not thy mind; nor let thy Soule contriue
+Against thy Mother ought; leaue her to heauen,
+And to those Thornes that in her bosome lodge,
+To pricke and sting her. Fare thee well at once;
+The Glow-worme showes the Matine to be neere,
+And gins to pale his vneffectuall Fire:
+Adue, adue, Hamlet: remember me.
+Enter.
+
+ Ham. Oh all you host of Heauen! Oh Earth; what els?
+And shall I couple Hell? Oh fie: hold my heart;
+And you my sinnewes, grow not instant Old;
+But beare me stiffely vp: Remember thee?
+I, thou poore Ghost, while memory holds a seate
+In this distracted Globe: Remember thee?
+Yea, from the Table of my Memory,
+Ile wipe away all triuiall fond Records,
+All sawes of Bookes, all formes, all presures past,
+That youth and obseruation coppied there;
+And thy Commandment all alone shall liue
+Within the Booke and Volume of my Braine,
+Vnmixt with baser matter; yes yes, by Heauen:
+Oh most pernicious woman!
+Oh Villaine, Villaine, smiling damned Villaine!
+My Tables, my Tables; meet it is I set it downe,
+That one may smile, and smile and be a Villaine;
+At least I'm sure it may be so in Denmarke;
+So Vnckle there you are: now to my word;
+It is; Adue, Adue, Remember me: I haue sworn't
+
+ Hor. & Mar. within. My Lord, my Lord.
+Enter Horatio and Marcellus.
+
+ Mar. Lord Hamlet
+
+ Hor. Heauen secure him
+
+ Mar. So be it
+
+ Hor. Illo, ho, ho, my Lord
+
+ Ham. Hillo, ho, ho, boy; come bird, come
+
+ Mar. How ist my Noble Lord?
+ Hor. What newes, my Lord?
+ Ham. Oh wonderfull!
+ Hor. Good my Lord tell it
+
+ Ham. No you'l reueale it
+
+ Hor. Not I, my Lord, by Heauen
+
+ Mar. Nor I, my Lord
+
+ Ham. How say you then, would heart of man once think it?
+But you'l be secret?
+ Both. I, by Heau'n, my Lord
+
+ Ham. There's nere a villaine dwelling in all Denmarke
+But hee's an arrant knaue
+
+ Hor. There needs no Ghost my Lord, come from the
+Graue, to tell vs this
+
+ Ham. Why right, you are i'th' right;
+And so, without more circumstance at all,
+I hold it fit that we shake hands, and part:
+You, as your busines and desires shall point you:
+For euery man ha's businesse and desire,
+Such as it is: and for mine owne poore part,
+Looke you, Ile goe pray
+
+ Hor. These are but wild and hurling words, my Lord
+
+ Ham. I'm sorry they offend you heartily:
+Yes faith, heartily
+
+ Hor. There's no offence my Lord
+
+ Ham. Yes, by Saint Patricke, but there is my Lord,
+And much offence too, touching this Vision heere:
+It is an honest Ghost, that let me tell you:
+For your desire to know what is betweene vs,
+O'remaster't as you may. And now good friends,
+As you are Friends, Schollers and Soldiers,
+Giue me one poore request
+
+ Hor. What is't my Lord? we will
+
+ Ham. Neuer make known what you haue seen to night
+
+ Both. My Lord, we will not
+
+ Ham. Nay, but swear't
+
+ Hor. Infaith my Lord, not I
+
+ Mar. Nor I my Lord: in faith
+
+ Ham. Vpon my sword
+
+ Marcell. We haue sworne my Lord already
+
+ Ham. Indeed, vpon my sword, Indeed
+
+ Gho. Sweare.
+
+Ghost cries vnder the Stage.
+
+ Ham. Ah ha boy, sayest thou so. Art thou there truepenny?
+Come one you here this fellow in the selleredge
+Consent to sweare
+
+ Hor. Propose the Oath my Lord
+
+ Ham. Neuer to speake of this that you haue seene.
+Sweare by my sword
+
+ Gho. Sweare
+
+ Ham. Hic & vbique? Then wee'l shift for grownd,
+Come hither Gentlemen,
+And lay your hands againe vpon my sword,
+Neuer to speake of this that you haue heard:
+Sweare by my Sword
+
+ Gho. Sweare
+
+ Ham. Well said old Mole, can'st worke i'th' ground so fast?
+A worthy Pioner, once more remoue good friends
+
+ Hor. Oh day and night: but this is wondrous strange
+
+ Ham. And therefore as a stranger giue it welcome.
+There are more things in Heauen and Earth, Horatio,
+Then are dream't of in our Philosophy. But come,
+Here as before, neuer so helpe you mercy,
+How strange or odde so ere I beare my selfe;
+(As I perchance heereafter shall thinke meet
+To put an Anticke disposition on:)
+That you at such time seeing me, neuer shall
+With Armes encombred thus, or thus, head shake;
+Or by pronouncing of some doubtfull Phrase;
+As well, we know, or we could and if we would,
+Or if we list to speake; or there be and if there might,
+Or such ambiguous giuing out to note,
+That you know ought of me; this not to doe:
+So grace and mercy at your most neede helpe you:
+Sweare
+
+ Ghost. Sweare
+
+ Ham. Rest, rest perturbed Spirit: so Gentlemen,
+With all my loue I doe commend me to you;
+And what so poore a man as Hamlet is,
+May doe t' expresse his loue and friending to you,
+God willing shall not lacke: let vs goe in together,
+And still your fingers on your lippes I pray,
+The time is out of ioynt: Oh cursed spight,
+That euer I was borne to set it right.
+Nay, come let's goe together.
+
+Exeunt.
+
+
+Actus Secundus.
+
+Enter Polonius, and Reynoldo.
+
+ Polon. Giue him his money, and these notes Reynoldo
+
+ Reynol. I will my Lord
+
+ Polon. You shall doe maruels wisely: good Reynoldo,
+Before you visite him you make inquiry
+Of his behauiour
+
+ Reynol. My Lord, I did intend it
+
+ Polon. Marry, well said;
+Very well said. Looke you Sir,
+Enquire me first what Danskers are in Paris;
+And how, and who; what meanes; and where they keepe:
+What company, at what expence: and finding
+By this encompassement and drift of question,
+That they doe know my sonne: Come you more neerer
+Then your particular demands will touch it,
+Take you as 'twere some distant knowledge of him,
+And thus I know his father and his friends,
+And in part him. Doe you marke this Reynoldo?
+ Reynol. I, very well my Lord
+
+ Polon. And in part him, but you may say not well;
+But if't be hee I meane, hees very wilde;
+Addicted so and so; and there put on him
+What forgeries you please; marry, none so ranke,
+As may dishonour him; take heed of that:
+But Sir, such wanton, wild, and vsuall slips,
+As are Companions noted and most knowne
+To youth and liberty
+
+ Reynol. As gaming my Lord
+
+ Polon. I, or drinking, fencing, swearing,
+Quarelling, drabbing. You may goe so farre
+
+ Reynol. My Lord that would dishonour him
+
+ Polon. Faith no, as you may season it in the charge;
+You must not put another scandall on him,
+That hee is open to Incontinencie;
+That's not my meaning: but breath his faults so quaintly,
+That they may seeme the taints of liberty;
+The flash and out-breake of a fiery minde,
+A sauagenes in vnreclaim'd bloud of generall assault
+
+ Reynol. But my good Lord
+
+ Polon. Wherefore should you doe this?
+ Reynol. I my Lord, I would know that
+
+ Polon. Marry Sir, heere's my drift,
+And I belieue it is a fetch of warrant:
+You laying these slight sulleyes on my Sonne,
+As 'twere a thing a little soil'd i'th' working:
+Marke you your party in conuerse; him you would sound,
+Hauing euer seene. In the prenominate crimes,
+The youth you breath of guilty, be assur'd
+He closes with you in this consequence:
+Good sir, or so, or friend, or Gentleman.
+According to the Phrase and the Addition,
+Of man and Country
+
+ Reynol. Very good my Lord
+
+ Polon. And then Sir does he this?
+He does: what was I about to say?
+I was about say somthing: where did I leaue?
+ Reynol. At closes in the consequence:
+At friend, or so, and Gentleman
+
+ Polon. At closes in the consequence, I marry,
+He closes with you thus. I know the Gentleman,
+I saw him yesterday, or tother day;
+Or then or then, with such and such; and as you say,
+There was he gaming, there o'retooke in's Rouse,
+There falling out at Tennis; or perchance,
+I saw him enter such a house of saile;
+Videlicet, a Brothell, or so forth. See you now;
+Your bait of falshood, takes this Cape of truth;
+And thus doe we of wisedome and of reach
+With windlesses, and with assaies of Bias,
+By indirections finde directions out:
+So by my former Lecture and aduice
+Shall you my Sonne; you haue me, haue you not?
+ Reynol. My Lord I haue
+
+ Polon. God buy you; fare you well
+
+ Reynol. Good my Lord
+
+ Polon. Obserue his inclination in your selfe
+
+ Reynol. I shall my Lord
+
+ Polon. And let him plye his Musicke
+
+ Reynol. Well, my Lord.
+Enter.
+
+Enter Ophelia.
+
+ Polon. Farewell:
+How now Ophelia, what's the matter?
+ Ophe. Alas my Lord, I haue beene so affrighted
+
+ Polon. With what, in the name of Heauen?
+ Ophe. My Lord, as I was sowing in my Chamber,
+Lord Hamlet with his doublet all vnbrac'd,
+No hat vpon his head, his stockings foul'd,
+Vngartred, and downe giued to his Anckle,
+Pale as his shirt, his knees knocking each other,
+And with a looke so pitious in purport,
+As if he had been loosed out of hell,
+To speake of horrors: he comes before me
+
+ Polon. Mad for thy Loue?
+ Ophe. My Lord, I doe not know: but truly I do feare it
+
+ Polon. What said he?
+ Ophe. He tooke me by the wrist, and held me hard;
+Then goes he to the length of all his arme;
+And with his other hand thus o're his brow,
+He fals to such perusall of my face,
+As he would draw it. Long staid he so,
+At last, a little shaking of mine Arme:
+And thrice his head thus wauing vp and downe;
+He rais'd a sigh, so pittious and profound,
+That it did seeme to shatter all his bulke,
+And end his being. That done, he lets me goe,
+And with his head ouer his shoulders turn'd,
+He seem'd to finde his way without his eyes,
+For out adores he went without their helpe;
+And to the last, bended their light on me
+
+ Polon. Goe with me, I will goe seeke the King,
+This is the very extasie of Loue,
+Whose violent property foredoes it selfe,
+And leads the will to desperate Vndertakings,
+As oft as any passion vnder Heauen,
+That does afflict our Natures. I am sorrie,
+What haue you giuen him any hard words of late?
+ Ophe. No my good Lord: but as you did command,
+I did repell his Letters, and deny'de
+His accesse to me
+
+ Pol. That hath made him mad.
+I am sorrie that with better speed and iudgement
+I had not quoted him. I feare he did but trifle,
+And meant to wracke thee: but beshrew my iealousie:
+It seemes it is as proper to our Age,
+To cast beyond our selues in our Opinions,
+As it is common for the yonger sort
+To lacke discretion. Come, go we to the King,
+This must be knowne, being kept close might moue
+More greefe to hide, then hate to vtter loue.
+
+Exeunt.
+
+
+Scena Secunda.
+
+Enter King, Queene, Rosincrane, and Guildensterne Cum alijs.
+
+ King. Welcome deere Rosincrance and Guildensterne.
+Moreouer, that we much did long to see you,
+The neede we haue to vse you, did prouoke
+Our hastie sending. Something haue you heard
+Of Hamlets transformation: so I call it,
+Since not th' exterior, nor the inward man
+Resembles that it was. What it should bee
+More then his Fathers death, that thus hath put him
+So much from th' vnderstanding of himselfe,
+I cannot deeme of. I intreat you both,
+That being of so young dayes brought vp with him:
+And since so Neighbour'd to his youth, and humour,
+That you vouchsafe your rest heere in our Court
+Some little time: so by your Companies
+To draw him on to pleasures, and to gather
+So much as from Occasions you may gleane,
+That open'd lies within our remedie
+
+ Qu. Good Gentlemen, he hath much talk'd of you,
+And sure I am, two men there are not liuing,
+To whom he more adheres. If it will please you
+To shew vs so much Gentrie, and good will,
+As to expend your time with vs a-while,
+For the supply and profit of our Hope,
+Your Visitation shall receiue such thankes
+As fits a Kings remembrance
+
+ Rosin. Both your Maiesties
+Might by the Soueraigne power you haue of vs,
+Put your dread pleasures, more into Command
+Then to Entreatie
+
+ Guil. We both obey,
+And here giue vp our selues, in the full bent,
+To lay our Seruices freely at your feete,
+To be commanded
+
+ King. Thankes Rosincrance, and gentle Guildensterne
+
+ Qu. Thankes Guildensterne and gentle Rosincrance.
+And I beseech you instantly to visit
+My too much changed Sonne.
+Go some of ye,
+And bring the Gentlemen where Hamlet is
+
+ Guil. Heauens make our presence and our practises
+Pleasant and helpfull to him.
+Enter.
+
+ Queene. Amen.
+Enter Polonius.
+
+ Pol. Th' Ambassadors from Norwey, my good Lord,
+Are ioyfully return'd
+
+ King. Thou still hast bin the father of good Newes
+
+ Pol. Haue I, my Lord? Assure you, my good Liege,
+I hold my dutie, as I hold my Soule,
+Both to my God, one to my gracious King:
+And I do thinke, or else this braine of mine
+Hunts not the traile of Policie, so sure
+As I haue vs'd to do: that I haue found
+The very cause of Hamlets Lunacie
+
+ King. Oh speake of that, that I do long to heare
+
+ Pol. Giue first admittance to th' Ambassadors,
+My Newes shall be the Newes to that great Feast
+
+ King. Thy selfe do grace to them, and bring them in.
+He tels me my sweet Queene, that he hath found
+The head and sourse of all your Sonnes distemper
+
+ Qu. I doubt it is no other, but the maine,
+His Fathers death, and our o're-hasty Marriage.
+Enter Polonius, Voltumand, and Cornelius.
+
+ King. Well, we shall sift him. Welcome good Frends:
+Say Voltumand, what from our Brother Norwey?
+ Volt. Most faire returne of Greetings, and Desires.
+Vpon our first, he sent out to suppresse
+His Nephewes Leuies, which to him appear'd
+To be a preparation 'gainst the Poleak:
+But better look'd into, he truly found
+It was against your Highnesse, whereat greeued,
+That so his Sicknesse, Age, and Impotence
+Was falsely borne in hand, sends out Arrests
+On Fortinbras, which he (in breefe) obeyes,
+Receiues rebuke from Norwey: and in fine,
+Makes Vow before his Vnkle, neuer more
+To giue th' assay of Armes against your Maiestie.
+Whereon old Norwey, ouercome with ioy,
+Giues him three thousand Crownes in Annuall Fee,
+And his Commission to imploy those Soldiers
+So leuied as before, against the Poleak:
+With an intreaty heerein further shewne,
+That it might please you to giue quiet passe
+Through your Dominions, for his Enterprize,
+On such regards of safety and allowance,
+As therein are set downe
+
+ King. It likes vs well:
+And at our more consider'd time wee'l read,
+Answer, and thinke vpon this Businesse.
+Meane time we thanke you, for your well-tooke Labour.
+Go to your rest, at night wee'l Feast together.
+Most welcome home.
+
+Exit Ambass.
+
+ Pol. This businesse is very well ended.
+My Liege, and Madam, to expostulate
+What Maiestie should be, what Dutie is,
+Why day is day; night, night; and time is time,
+Were nothing but to waste Night, Day, and Time.
+Therefore, since Breuitie is the Soule of Wit,
+And tediousnesse, the limbes and outward flourishes,
+I will be breefe. Your Noble Sonne is mad:
+Mad call I it; for to define true Madnesse,
+What is't, but to be nothing else but mad.
+But let that go
+
+ Qu. More matter, with lesse Art
+
+ Pol. Madam, I sweare I vse no Art at all:
+That he is mad, 'tis true: 'Tis true 'tis pittie,
+And pittie it is true: A foolish figure,
+But farewell it: for I will vse no Art.
+Mad let vs grant him then: and now remaines
+That we finde out the cause of this effect,
+Or rather say, the cause of this defect;
+For this effect defectiue, comes by cause,
+Thus it remaines, and the remainder thus. Perpend,
+I haue a daughter: haue, whil'st she is mine,
+Who in her Dutie and Obedience, marke,
+Hath giuen me this: now gather, and surmise.
+
+The Letter.
+
+To the Celestiall, and my Soules Idoll, the most beautifed Ophelia.
+That's an ill Phrase, a vilde Phrase, beautified is a vilde
+Phrase: but you shall heare these in her excellent white
+bosome, these
+
+ Qu. Came this from Hamlet to her
+
+ Pol. Good Madam stay awhile, I will be faithfull.
+Doubt thou, the Starres are fire,
+Doubt, that the Sunne doth moue:
+Doubt Truth to be a Lier,
+But neuer Doubt, I loue.
+O deere Ophelia, I am ill at these Numbers: I haue not Art to
+reckon my grones; but that I loue thee best, oh most Best beleeue
+it. Adieu.
+Thine euermore most deere Lady, whilst this
+Machine is to him, Hamlet.
+This in Obedience hath my daughter shew'd me:
+And more aboue hath his soliciting,
+As they fell out by Time, by Meanes, and Place,
+All giuen to mine eare
+
+ King. But how hath she receiu'd his Loue?
+ Pol. What do you thinke of me?
+ King. As of a man, faithfull and Honourable
+
+ Pol. I wold faine proue so. But what might you think?
+When I had seene this hot loue on the wing,
+As I perceiued it, I must tell you that
+Before my Daughter told me what might you
+Or my deere Maiestie your Queene heere, think,
+If I had playd the Deske or Table-booke,
+Or giuen my heart a winking, mute and dumbe,
+Or look'd vpon this Loue, with idle sight,
+What might you thinke? No, I went round to worke,
+And (my yong Mistris) thus I did bespeake
+Lord Hamlet is a Prince out of thy Starre,
+This must not be: and then, I Precepts gaue her,
+That she should locke her selfe from his Resort,
+Admit no Messengers, receiue no Tokens:
+Which done, she tooke the Fruites of my Aduice,
+And he repulsed. A short Tale to make,
+Fell into a Sadnesse, then into a Fast,
+Thence to a Watch, thence into a Weaknesse,
+Thence to a Lightnesse, and by this declension
+Into the Madnesse whereon now he raues,
+And all we waile for
+
+ King. Do you thinke 'tis this?
+ Qu. It may be very likely
+
+ Pol. Hath there bene such a time, I'de fain know that,
+That I haue possitiuely said, 'tis so,
+When it prou'd otherwise?
+ King. Not that I know
+
+ Pol. Take this from this; if this be otherwise,
+If Circumstances leade me, I will finde
+Where truth is hid, though it were hid indeede
+Within the Center
+
+ King. How may we try it further?
+ Pol. You know sometimes
+He walkes foure houres together, heere
+In the Lobby
+
+ Qu. So he ha's indeed
+
+ Pol. At such a time Ile loose my Daughter to him,
+Be you and I behinde an Arras then,
+Marke the encounter: If he loue her not,
+And be not from his reason falne thereon;
+Let me be no Assistant for a State,
+And keepe a Farme and Carters
+
+ King. We will try it.
+Enter Hamlet reading on a Booke.
+
+ Qu. But looke where sadly the poore wretch
+Comes reading
+
+ Pol. Away I do beseech you, both away,
+Ile boord him presently.
+
+Exit King & Queen.
+
+Oh giue me leaue. How does my good Lord Hamlet?
+ Ham. Well, God-a-mercy
+
+ Pol. Do you know me, my Lord?
+ Ham. Excellent, excellent well: y'are a Fishmonger
+
+ Pol. Not I my Lord
+
+ Ham. Then I would you were so honest a man
+
+ Pol. Honest, my Lord?
+ Ham. I sir, to be honest as this world goes, is to bee
+one man pick'd out of two thousand
+
+ Pol. That's very true, my Lord
+
+ Ham. For if the Sun breed Magots in a dead dogge,
+being a good kissing Carrion-
+Haue you a daughter?
+ Pol. I haue my Lord
+
+ Ham. Let her not walke i'thSunne: Conception is a
+blessing, but not as your daughter may conceiue. Friend
+looke too't
+
+ Pol. How say you by that? Still harping on my daughter:
+yet he knew me not at first; he said I was a Fishmonger:
+he is farre gone, farre gone: and truly in my youth,
+I suffred much extreamity for loue: very neere this. Ile
+speake to him againe. What do you read my Lord?
+ Ham. Words, words, words
+
+ Pol. What is the matter, my Lord?
+ Ham. Betweene who?
+ Pol. I meane the matter you meane, my Lord
+
+ Ham. Slanders Sir: for the Satyricall slaue saies here,
+that old men haue gray Beards; that their faces are wrinkled;
+their eyes purging thicke Amber, or Plum-Tree
+Gumme: and that they haue a plentifull locke of Wit,
+together with weake Hammes. All which Sir, though I
+most powerfully, and potently beleeue; yet I holde it
+not Honestie to haue it thus set downe: For you your
+selfe Sir, should be old as I am, if like a Crab you could
+go backward
+
+ Pol. Though this be madnesse,
+Yet there is Method in't: will you walke
+Out of the ayre my Lord?
+ Ham. Into my Graue?
+ Pol. Indeed that is out o'th' Ayre:
+How pregnant (sometimes) his Replies are?
+A happinesse,
+That often Madnesse hits on,
+Which Reason and Sanitie could not
+So prosperously be deliuer'd of.
+I will leaue him,
+And sodainely contriue the meanes of meeting
+Betweene him, and my daughter.
+My Honourable Lord, I will most humbly
+Take my leaue of you
+
+ Ham. You cannot Sir take from me any thing, that I
+will more willingly part withall, except my life, my
+life
+
+ Polon. Fare you well my Lord
+
+ Ham. These tedious old fooles
+
+ Polon. You goe to seeke my Lord Hamlet; there
+hee is.
+Enter Rosincran and Guildensterne.
+
+ Rosin. God saue you Sir
+
+ Guild. Mine honour'd Lord?
+ Rosin. My most deare Lord?
+ Ham. My excellent good friends? How do'st thou
+Guildensterne? Oh, Rosincrane; good Lads: How doe ye
+both?
+ Rosin. As the indifferent Children of the earth
+
+ Guild. Happy, in that we are not ouer-happy: on Fortunes
+Cap, we are not the very Button
+
+ Ham. Nor the Soales of her Shoo?
+ Rosin. Neither my Lord
+
+ Ham. Then you liue about her waste, or in the middle
+of her fauour?
+ Guil. Faith, her priuates, we
+
+ Ham. In the secret parts of Fortune? Oh, most true:
+she is a Strumpet. What's the newes?
+ Rosin. None my Lord; but that the World's growne
+honest
+
+ Ham. Then is Doomesday neere: But your newes is
+not true. Let me question more in particular: what haue
+you my good friends, deserued at the hands of Fortune,
+that she sends you to Prison hither?
+ Guil. Prison, my Lord?
+ Ham. Denmark's a Prison
+
+ Rosin. Then is the World one
+
+ Ham. A goodly one, in which there are many Confines,
+Wards, and Dungeons; Denmarke being one o'th'
+worst
+
+ Rosin. We thinke not so my Lord
+
+ Ham. Why then 'tis none to you; for there is nothing
+either good or bad, but thinking makes it so: to me it is
+a prison
+
+ Rosin. Why then your Ambition makes it one: 'tis
+too narrow for your minde
+
+ Ham. O God, I could be bounded in a nutshell, and
+count my selfe a King of infinite space; were it not that
+I haue bad dreames
+
+ Guil. Which dreames indeed are Ambition: for the
+very substance of the Ambitious, is meerely the shadow
+of a Dreame
+
+ Ham. A dreame it selfe is but a shadow
+
+ Rosin. Truely, and I hold Ambition of so ayry and
+light a quality, that it is but a shadowes shadow
+
+ Ham. Then are our Beggers bodies; and our Monarchs
+and out-stretcht Heroes the Beggers Shadowes:
+shall wee to th' Court: for, by my fey I cannot reason?
+ Both. Wee'l wait vpon you
+
+ Ham. No such matter. I will not sort you with the
+rest of my seruants: for to speake to you like an honest
+man: I am most dreadfully attended; but in the beaten
+way of friendship, What make you at Elsonower?
+ Rosin. To visit you my Lord, no other occasion
+
+ Ham. Begger that I am, I am euen poore in thankes;
+but I thanke you: and sure deare friends my thanks
+are too deare a halfepeny; were you not sent for? Is it
+your owne inclining? Is it a free visitation? Come,
+deale iustly with me: come, come; nay speake
+
+ Guil. What should we say my Lord?
+ Ham. Why any thing. But to the purpose; you were
+sent for; and there is a kinde confession in your lookes;
+which your modesties haue not craft enough to color,
+I know the good King & Queene haue sent for you
+
+ Rosin. To what end my Lord?
+ Ham. That you must teach me: but let mee coniure
+you by the rights of our fellowship, by the consonancy of
+our youth, by the Obligation of our euer-preserued loue,
+and by what more deare, a better proposer could charge
+you withall; be euen and direct with me, whether you
+were sent for or no
+
+ Rosin. What say you?
+ Ham. Nay then I haue an eye of you: if you loue me
+hold not off
+
+ Guil. My Lord, we were sent for
+
+ Ham. I will tell you why; so shall my anticipation
+preuent your discouery of your secricie to the King and
+Queene: moult no feather, I haue of late, but wherefore
+I know not, lost all my mirth, forgone all custome of exercise;
+and indeed, it goes so heauenly with my disposition;
+that this goodly frame the Earth, seemes to me a sterrill
+Promontory; this most excellent Canopy the Ayre,
+look you, this braue ore-hanging, this Maiesticall Roofe,
+fretted with golden fire: why, it appeares no other thing
+to mee, then a foule and pestilent congregation of vapours.
+What a piece of worke is a man! how Noble in
+Reason? how infinite in faculty? in forme and mouing
+how expresse and admirable? in Action, how like an Angel?
+in apprehension, how like a God? the beauty of the
+world, the Parragon of Animals; and yet to me, what is
+this Quintessence of Dust? Man delights not me; no,
+nor Woman neither; though by your smiling you seeme
+to say so
+
+ Rosin. My Lord, there was no such stuffe in my
+thoughts
+
+ Ham. Why did you laugh, when I said, Man delights
+not me?
+ Rosin. To thinke, my Lord, if you delight not in Man,
+what Lenton entertainment the Players shall receiue
+from you: wee coated them on the way, and hither are
+they comming to offer you Seruice
+
+ Ham. He that playes the King shall be welcome; his
+Maiesty shall haue Tribute of mee: the aduenturous
+Knight shal vse his Foyle and Target: the Louer shall
+not sigh gratis, the humorous man shall end his part in
+peace: the Clowne shall make those laugh whose lungs
+are tickled a'th' sere: and the Lady shall say her minde
+freely; or the blanke Verse shall halt for't: what Players
+are they?
+ Rosin. Euen those you were wont to take delight in
+the Tragedians of the City
+
+ Ham. How chances it they trauaile? their residence
+both in reputation and profit was better both
+wayes
+
+ Rosin. I thinke their Inhibition comes by the meanes
+of the late Innouation?
+ Ham. Doe they hold the same estimation they did
+when I was in the City? Are they so follow'd?
+ Rosin. No indeed, they are not
+
+ Ham. How comes it? doe they grow rusty?
+ Rosin. Nay, their indeauour keepes in the wonted
+pace; But there is Sir an ayrie of Children, little
+Yases, that crye out on the top of question; and
+are most tyrannically clap't for't: these are now the
+fashion, and so be-ratled the common Stages (so they
+call them) that many wearing Rapiers, are affraide of
+Goose-quils, and dare scarse come thither
+
+ Ham. What are they Children? Who maintains 'em?
+How are they escorted? Will they pursue the Quality no
+longer then they can sing? Will they not say afterwards
+if they should grow themselues to common Players (as
+it is most like if their meanes are not better) their Writers
+do them wrong, to make them exclaim against their
+owne Succession
+
+ Rosin. Faith there ha's bene much to do on both sides:
+and the Nation holds it no sinne, to tarre them to Controuersie.
+There was for a while, no mony bid for argument,
+vnlesse the Poet and the Player went to Cuffes in
+the Question
+
+ Ham. Is't possible?
+ Guild. Oh there ha's beene much throwing about of
+Braines
+
+ Ham. Do the Boyes carry it away?
+ Rosin. I that they do my Lord. Hercules & his load too
+
+ Ham. It is not strange: for mine Vnckle is King of
+Denmarke, and those that would make mowes at him
+while my Father liued; giue twenty, forty, an hundred
+Ducates a peece, for his picture in Little. There is something
+in this more then Naturall, if Philosophie could
+finde it out.
+
+Flourish for the Players.
+
+ Guil. There are the Players
+
+ Ham. Gentlemen, you are welcom to Elsonower: your
+hands, come: The appurtenance of Welcome, is Fashion
+and Ceremony. Let me comply with you in the Garbe,
+lest my extent to the Players (which I tell you must shew
+fairely outward) should more appeare like entertainment
+then yours. You are welcome: but my Vnckle Father,
+and Aunt Mother are deceiu'd
+
+ Guil. In what my deere Lord?
+ Ham. I am but mad North, North-West: when the
+Winde is Southerly, I know a Hawke from a Handsaw.
+Enter Polonius.
+
+ Pol. Well be with you Gentlemen
+
+ Ham. Hearke you Guildensterne, and you too: at each
+eare a hearer: that great Baby you see there, is not yet
+out of his swathing clouts
+
+ Rosin. Happily he's the second time come to them: for
+they say, an old man is twice a childe
+
+ Ham. I will Prophesie. Hee comes to tell me of the
+Players. Mark it, you say right Sir: for a Monday morning
+'twas so indeed
+
+ Pol. My Lord, I haue Newes to tell you
+
+ Ham. My Lord, I haue Newes to tell you.
+When Rossius an Actor in Rome-
+ Pol. The Actors are come hither my Lord
+
+ Ham. Buzze, buzze
+
+ Pol. Vpon mine Honor
+
+ Ham. Then can each Actor on his Asse-
+ Polon. The best Actors in the world, either for Tragedie,
+Comedie, Historie, Pastorall:
+Pastoricall-Comicall-Historicall-Pastorall:
+Tragicall-Historicall: Tragicall-Comicall-Historicall-Pastorall:
+Scene indiuidible: or Poem
+vnlimited. Seneca cannot be too heauy, nor Plautus
+too light, for the law of Writ, and the Liberty. These are
+the onely men
+
+ Ham. O Iephta Iudge of Israel, what a Treasure had'st
+thou?
+ Pol. What a Treasure had he, my Lord?
+ Ham. Why one faire Daughter, and no more,
+The which he loued passing well
+
+ Pol. Still on my Daughter
+
+ Ham. Am I not i'th' right old Iephta?
+ Polon. If you call me Iephta my Lord, I haue a daughter
+that I loue passing well
+
+ Ham. Nay that followes not
+
+ Polon. What followes then, my Lord?
+ Ha. Why, As by lot, God wot: and then you know, It
+came to passe, as most like it was: The first rowe of the
+Pons Chanson will shew you more. For looke where my
+Abridgements come.
+Enter foure or fiue Players.
+
+Y'are welcome Masters, welcome all. I am glad to see
+thee well: Welcome good Friends. Oh my olde Friend?
+Thy face is valiant since I saw thee last: Com'st thou to
+beard me in Denmarke? What, my yong Lady and Mistris?
+Byrlady your Ladiship is neerer Heauen then when
+I saw you last, by the altitude of a Choppine. Pray God
+your voice like a peece of vncurrant Gold be not crack'd
+within the ring. Masters, you are all welcome: wee'l e'ne
+to't like French Faulconers, flie at any thing we see: wee'l
+haue a Speech straight. Come giue vs a tast of your quality:
+come, a passionate speech
+
+ 1.Play. What speech, my Lord?
+ Ham. I heard thee speak me a speech once, but it was
+neuer Acted: or if it was, not aboue once, for the Play I
+remember pleas'd not the Million, 'twas Cauiarie to the
+Generall: but it was (as I receiu'd it, and others, whose
+iudgement in such matters, cried in the top of mine) an
+excellent Play; well digested in the Scoenes, set downe
+with as much modestie, as cunning. I remember one said,
+there was no Sallets in the lines, to make the matter sauory;
+nor no matter in the phrase, that might indite the
+Author of affectation, but cal'd it an honest method. One
+cheefe Speech in it, I cheefely lou'd, 'twas Aeneas Tale
+to Dido, and thereabout of it especially, where he speaks
+of Priams slaughter. If it liue in your memory, begin at
+this Line, let me see, let me see: The rugged Pyrrhus like
+th'Hyrcanian Beast. It is not so: it begins with Pyrrhus
+The rugged Pyrrhus, he whose Sable Armes
+Blacke as his purpose, did the night resemble
+When he lay couched in the Ominous Horse,
+Hath now this dread and blacke Complexion smear'd
+With Heraldry more dismall: Head to foote
+Now is he to take Geulles, horridly Trick'd
+With blood of Fathers, Mothers, Daughters, Sonnes,
+Bak'd and impasted with the parching streets,
+That lend a tyrannous, and damned light
+To their vilde Murthers, roasted in wrath and fire,
+And thus o're-sized with coagulate gore,
+With eyes like Carbuncles, the hellish Pyrrhus
+Olde Grandsire Priam seekes
+
+ Pol. Fore God, my Lord, well spoken, with good accent,
+and good discretion
+
+ 1.Player. Anon he findes him,
+Striking too short at Greekes. His anticke Sword,
+Rebellious to his Arme, lyes where it falles
+Repugnant to command: vnequall match,
+Pyrrhus at Priam driues, in Rage strikes wide:
+But with the whiffe and winde of his fell Sword,
+Th' vnnerued Father fals. Then senselesse Illium,
+Seeming to feele his blow, with flaming top
+Stoopes to his Bace, and with a hideous crash
+Takes Prisoner Pyrrhus eare. For loe, his Sword
+Which was declining on the Milkie head
+Of Reuerend Priam, seem'd i'th' Ayre to sticke:
+So as a painted Tyrant Pyrrhus stood,
+And like a Newtrall to his will and matter, did nothing.
+But as we often see against some storme,
+A silence in the Heauens, the Racke stand still,
+The bold windes speechlesse, and the Orbe below
+As hush as death: Anon the dreadfull Thunder
+Doth rend the Region. So after Pyrrhus pause,
+A rowsed Vengeance sets him new a-worke,
+And neuer did the Cyclops hammers fall
+On Mars his Armours, forg'd for proofe Eterne,
+With lesse remorse then Pyrrhus bleeding sword
+Now falles on Priam.
+Out, out, thou Strumpet-Fortune, all you Gods,
+In generall Synod take away her power:
+Breake all the Spokes and Fallies from her wheele,
+And boule the round Naue downe the hill of Heauen,
+As low as to the Fiends
+
+ Pol. This is too long
+
+ Ham. It shall to'th Barbars, with your beard. Prythee
+say on: He's for a Iigge, or a tale of Baudry, or hee
+sleepes. Say on; come to Hecuba
+
+ 1.Play. But who, O who, had seen the inobled Queen
+
+ Ham. The inobled Queene?
+ Pol. That's good: Inobled Queene is good
+
+ 1.Play. Run bare-foot vp and downe,
+Threatning the flame
+With Bisson Rheume: A clout about that head,
+Where late the Diadem stood, and for a Robe
+About her lanke and all ore-teamed Loines,
+A blanket in th' Alarum of feare caught vp.
+Who this had seene, with tongue in Venome steep'd,
+'Gainst Fortunes State, would Treason haue pronounc'd?
+But if the Gods themselues did see her then,
+When she saw Pyrrhus make malicious sport
+In mincing with his Sword her Husbands limbes,
+The instant Burst of Clamour that she made
+(Vnlesse things mortall moue them not at all)
+Would haue made milche the Burning eyes of Heauen,
+And passion in the Gods
+
+ Pol. Looke where he ha's not turn'd his colour, and
+ha's teares in's eyes. Pray you no more
+
+ Ham. 'Tis well, Ile haue thee speake out the rest,
+soone. Good my Lord, will you see the Players wel bestow'd.
+Do ye heare, let them be well vs'd: for they are
+the Abstracts and breefe Chronicles of the time. After
+your death, you were better haue a bad Epitaph, then
+their ill report while you liued
+
+ Pol. My Lord, I will vse them according to their desart
+
+ Ham. Gods bodykins man, better. Vse euerie man
+after his desart, and who should scape whipping: vse
+them after your own Honor and Dignity. The lesse they
+deserue, the more merit is in your bountie. Take them
+in
+
+ Pol. Come sirs.
+
+Exit Polon.
+
+ Ham. Follow him Friends: wee'l heare a play to morrow.
+Dost thou heare me old Friend, can you play the
+murther of Gonzago?
+ Play. I my Lord
+
+ Ham. Wee'l ha't to morrow night. You could for a
+need study a speech of some dosen or sixteene lines, which
+I would set downe, and insert in't? Could ye not?
+ Play. I my Lord
+
+ Ham. Very well. Follow that Lord, and looke you
+mock him not. My good Friends, Ile leaue you til night
+you are welcome to Elsonower?
+ Rosin. Good my Lord.
+
+Exeunt.
+
+Manet Hamlet.
+
+ Ham. I so, God buy'ye: Now I am alone.
+Oh what a Rogue and Pesant slaue am I?
+Is it not monstrous that this Player heere,
+But in a Fixion, in a dreame of Passion,
+Could force his soule so to his whole conceit,
+That from her working, all his visage warm'd;
+Teares in his eyes, distraction in's Aspect,
+A broken voyce, and his whole Function suiting
+With Formes, to his Conceit? And all for nothing?
+For Hecuba?
+What's Hecuba to him, or he to Hecuba,
+That he should weepe for her? What would he doe,
+Had he the Motiue and the Cue for passion
+That I haue? He would drowne the Stage with teares,
+And cleaue the generall eare with horrid speech:
+Make mad the guilty, and apale the free,
+Confound the ignorant, and amaze indeed,
+The very faculty of Eyes and Eares. Yet I,
+A dull and muddy-metled Rascall, peake
+Like Iohn a-dreames, vnpregnant of my cause,
+And can say nothing: No, not for a King,
+Vpon whose property, and most deere life,
+A damn'd defeate was made. Am I a Coward?
+Who calles me Villaine? breakes my pate a-crosse?
+Pluckes off my Beard, and blowes it in my face?
+Tweakes me by'th' Nose? giues me the Lye i'th' Throate,
+As deepe as to the Lungs? Who does me this?
+Ha? Why I should take it: for it cannot be,
+But I am Pigeon-Liuer'd, and lacke Gall
+To make Oppression bitter, or ere this,
+I should haue fatted all the Region Kites
+With this Slaues Offall, bloudy: a Bawdy villaine,
+Remorselesse, Treacherous, Letcherous, kindles villaine!
+Oh Vengeance!
+Who? What an Asse am I? I sure, this is most braue,
+That I, the Sonne of the Deere murthered,
+Prompted to my Reuenge by Heauen, and Hell,
+Must (like a Whore) vnpacke my heart with words,
+And fall a Cursing like a very Drab.
+A Scullion? Fye vpon't: Foh. About my Braine.
+I haue heard, that guilty Creatures sitting at a Play,
+Haue by the very cunning of the Scoene,
+Bene strooke so to the soule, that presently
+They haue proclaim'd their Malefactions.
+For Murther, though it haue no tongue, will speake
+With most myraculous Organ. Ile haue these Players,
+Play something like the murder of my Father,
+Before mine Vnkle. Ile obserue his lookes,
+Ile rent him to the quicke: If he but blench
+I know my course. The Spirit that I haue seene
+May be the Diuell, and the Diuel hath power
+T' assume a pleasing shape, yea and perhaps
+Out of my Weaknesse, and my Melancholly,
+As he is very potent with such Spirits,
+Abuses me to damne me. Ile haue grounds
+More Relatiue then this: The Play's the thing,
+Wherein Ile catch the Conscience of the King.
+
+Exit
+
+Enter King, Queene, Polonius, Ophelia, Rosincrance,
+Guildenstern, and
+Lords.
+
+ King. And can you by no drift of circumstance
+Get from him why he puts on this Confusion:
+Grating so harshly all his dayes of quiet
+With turbulent and dangerous Lunacy
+
+ Rosin. He does confesse he feeles himselfe distracted,
+But from what cause he will by no meanes speake
+
+ Guil. Nor do we finde him forward to be sounded,
+But with a crafty Madnesse keepes aloofe:
+When we would bring him on to some Confession
+Of his true state
+
+ Qu. Did he receiue you well?
+ Rosin. Most like a Gentleman
+
+ Guild. But with much forcing of his disposition
+
+ Rosin. Niggard of question, but of our demands
+Most free in his reply
+
+ Qu. Did you assay him to any pastime?
+ Rosin. Madam, it so fell out, that certaine Players
+We ore-wrought on the way: of these we told him,
+And there did seeme in him a kinde of ioy
+To heare of it: They are about the Court,
+And (as I thinke) they haue already order
+This night to play before him
+
+ Pol. 'Tis most true:
+And he beseech'd me to intreate your Maiesties
+To heare, and see the matter
+
+ King. With all my heart, and it doth much content me
+To heare him so inclin'd. Good Gentlemen,
+Giue him a further edge, and driue his purpose on
+To these delights
+
+ Rosin. We shall my Lord.
+
+Exeunt.
+
+ King. Sweet Gertrude leaue vs too,
+For we haue closely sent for Hamlet hither,
+That he, as 'twere by accident, may there
+Affront Ophelia. Her Father, and my selfe (lawful espials)
+Will so bestow our selues, that seeing vnseene
+We may of their encounter frankely iudge,
+And gather by him, as he is behaued,
+If't be th' affliction of his loue, or no.
+That thus he suffers for
+
+ Qu. I shall obey you,
+And for your part Ophelia, I do wish
+That your good Beauties be the happy cause
+Of Hamlets wildenesse: so shall I hope your Vertues
+Will bring him to his wonted way againe,
+To both your Honors
+
+ Ophe. Madam, I wish it may
+
+ Pol. Ophelia, walke you heere. Gracious so please ye
+We will bestow our selues: Reade on this booke,
+That shew of such an exercise may colour
+Your lonelinesse. We are oft too blame in this,
+'Tis too much prou'd, that with Deuotions visage,
+And pious Action, we do surge o're
+The diuell himselfe
+
+ King. Oh 'tis true:
+How smart a lash that speech doth giue my Conscience?
+The Harlots Cheeke beautied with plaist'ring Art
+Is not more vgly to the thing that helpes it,
+Then is my deede, to my most painted word.
+Oh heauie burthen!
+ Pol. I heare him comming, let's withdraw my Lord.
+
+Exeunt.
+
+Enter Hamlet.
+
+ Ham. To be, or not to be, that is the Question:
+Whether 'tis Nobler in the minde to suffer
+The Slings and Arrowes of outragious Fortune,
+Or to take Armes against a Sea of troubles,
+And by opposing end them: to dye, to sleepe
+No more; and by a sleepe, to say we end
+The Heart-ake, and the thousand Naturall shockes
+That Flesh is heyre too? 'Tis a consummation
+Deuoutly to be wish'd. To dye to sleepe,
+To sleepe, perchance to Dreame; I, there's the rub,
+For in that sleepe of death, what dreames may come,
+When we haue shuffel'd off this mortall coile,
+Must giue vs pawse. There's the respect
+That makes Calamity of so long life:
+For who would beare the Whips and Scornes of time,
+The Oppressors wrong, the poore mans Contumely,
+The pangs of dispriz'd Loue, the Lawes delay,
+The insolence of Office, and the Spurnes
+That patient merit of the vnworthy takes,
+When he himselfe might his Quietus make
+With a bare Bodkin? Who would these Fardles beare
+To grunt and sweat vnder a weary life,
+But that the dread of something after death,
+The vndiscouered Countrey, from whose Borne
+No Traueller returnes, Puzels the will,
+And makes vs rather beare those illes we haue,
+Then flye to others that we know not of.
+Thus Conscience does make Cowards of vs all,
+And thus the Natiue hew of Resolution
+Is sicklied o're, with the pale cast of Thought,
+And enterprizes of great pith and moment,
+With this regard their Currants turne away,
+And loose the name of Action. Soft you now,
+The faire Ophelia? Nimph, in thy Orizons
+Be all my sinnes remembred
+
+ Ophe. Good my Lord,
+How does your Honor for this many a day?
+ Ham. I humbly thanke you: well, well, well
+
+ Ophe. My Lord, I haue Remembrances of yours,
+That I haue longed long to re-deliuer.
+I pray you now, receiue them
+
+ Ham. No, no, I neuer gaue you ought
+
+ Ophe. My honor'd Lord, I know right well you did,
+And with them words of so sweet breath compos'd,
+As made the things more rich, then perfume left:
+Take these againe, for to the Noble minde
+Rich gifts wax poore, when giuers proue vnkinde.
+There my Lord
+
+ Ham. Ha, ha: Are you honest?
+ Ophe. My Lord
+
+ Ham. Are you faire?
+ Ophe. What meanes your Lordship?
+ Ham. That if you be honest and faire, your Honesty
+should admit no discourse to your Beautie
+
+ Ophe. Could Beautie my Lord, haue better Comerce
+then your Honestie?
+ Ham. I trulie: for the power of Beautie, will sooner
+transforme Honestie from what is, to a Bawd, then the
+force of Honestie can translate Beautie into his likenesse.
+This was sometime a Paradox, but now the time giues it
+proofe. I did loue you once
+
+ Ophe. Indeed my Lord, you made me beleeue so
+
+ Ham. You should not haue beleeued me. For vertue
+cannot so innocculate our old stocke, but we shall rellish
+of it. I loued you not
+
+ Ophe. I was the more deceiued
+
+ Ham. Get thee to a Nunnerie. Why would'st thou
+be a breeder of Sinners? I am my selfe indifferent honest,
+but yet I could accuse me of such things, that it were better
+my Mother had not borne me. I am very prowd, reuengefull,
+Ambitious, with more offences at my becke,
+then I haue thoughts to put them in imagination, to giue
+them shape, or time to acte them in. What should such
+Fellowes as I do, crawling betweene Heauen and Earth.
+We are arrant Knaues all, beleeue none of vs. Goe thy
+wayes to a Nunnery. Where's your Father?
+ Ophe. At home, my Lord
+
+ Ham. Let the doores be shut vpon him, that he may
+play the Foole no way, but in's owne house. Farewell
+
+ Ophe. O helpe him, you sweet Heauens
+
+ Ham. If thou doest Marry, Ile giue thee this Plague
+for thy Dowrie. Be thou as chast as Ice, as pure as Snow,
+thou shalt not escape Calumny. Get thee to a Nunnery.
+Go, Farewell. Or if thou wilt needs Marry, marry a fool:
+for Wise men know well enough, what monsters you
+make of them. To a Nunnery go, and quickly too. Farwell
+
+ Ophe. O heauenly Powers, restore him
+
+ Ham. I haue heard of your pratlings too wel enough.
+God has giuen you one pace, and you make your selfe another:
+you gidge, you amble, and you lispe, and nickname
+Gods creatures, and make your Wantonnesse, your Ignorance.
+Go too, Ile no more on't, it hath made me mad.
+I say, we will haue no more Marriages. Those that are
+married already, all but one shall liue, the rest shall keep
+as they are. To a Nunnery, go.
+
+Exit Hamlet.
+
+ Ophe. O what a Noble minde is heere o're-throwne?
+The Courtiers, Soldiers, Schollers: Eye, tongue, sword,
+Th' expectansie and Rose of the faire State,
+The glasse of Fashion, and the mould of Forme,
+Th' obseru'd of all Obseruers, quite, quite downe.
+Haue I of Ladies most deiect and wretched,
+That suck'd the Honie of his Musicke Vowes:
+Now see that Noble, and most Soueraigne Reason,
+Like sweet Bels iangled out of tune, and harsh,
+That vnmatch'd Forme and Feature of blowne youth,
+Blasted with extasie. Oh woe is me,
+T'haue seene what I haue seene: see what I see.
+Enter King, and Polonius.
+
+ King. Loue? His affections do not that way tend,
+Nor what he spake, though it lack'd Forme a little,
+Was not like Madnesse. There's something in his soule?
+O're which his Melancholly sits on brood,
+And I do doubt the hatch, and the disclose
+Will be some danger, which to preuent
+I haue in quicke determination
+Thus set it downe. He shall with speed to England
+For the demand of our neglected Tribute:
+Haply the Seas and Countries different
+With variable Obiects, shall expell
+This something setled matter in his heart:
+Whereon his Braines still beating, puts him thus
+From fashion of himselfe. What thinke you on't?
+ Pol. It shall do well. But yet do I beleeue
+The Origin and Commencement of this greefe
+Sprung from neglected loue. How now Ophelia?
+You neede not tell vs, what Lord Hamlet saide,
+We heard it all. My Lord, do as you please,
+But if you hold it fit after the Play,
+Let his Queene Mother all alone intreat him
+To shew his Greefes: let her be round with him,
+And Ile be plac'd so, please you in the eare
+Of all their Conference. If she finde him not,
+To England send him: Or confine him where
+Your wisedome best shall thinke
+
+ King. It shall be so:
+Madnesse in great Ones, must not vnwatch'd go.
+
+Exeunt.
+
+Enter Hamlet, and two or three of the Players.
+
+ Ham. Speake the Speech I pray you, as I pronounc'd
+it to you trippingly on the Tongue: But if you mouth it,
+as many of your Players do, I had as liue the Town-Cryer
+had spoke my Lines: Nor do not saw the Ayre too much
+your hand thus, but vse all gently; for in the verie Torrent,
+Tempest, and (as I say) the Whirle-winde of
+Passion, you must acquire and beget a Temperance that
+may giue it Smoothnesse. O it offends mee to the Soule,
+to see a robustious Pery-wig-pated Fellow, teare a Passion
+to tatters, to verie ragges, to split the eares of the
+Groundlings: who (for the most part) are capeable of
+nothing, but inexplicable dumbe shewes, & noise: I could
+haue such a Fellow whipt for o're-doing Termagant: it
+outHerod's Herod. Pray you auoid it
+
+ Player. I warrant your Honor
+
+ Ham. Be not too tame neyther: but let your owne
+Discretion be your Tutor. Sute the Action to the Word,
+the Word to the Action, with this speciall obseruance:
+That you ore-stop not the modestie of Nature; for any
+thing so ouer-done, is fro[m] the purpose of Playing, whose
+end both at the first and now, was and is, to hold as 'twer
+the Mirrour vp to Nature; to shew Vertue her owne
+Feature, Scorne her owne Image, and the verie Age and
+Bodie of the Time, his forme and pressure. Now, this
+ouer-done, or come tardie off, though it make the vnskilfull
+laugh, cannot but make the Iudicious greeue; The
+censure of the which One, must in your allowance o'reway
+a whole Theater of Others. Oh, there bee Players
+that I haue seene Play, and heard others praise, and that
+highly (not to speake it prophanely) that neyther hauing
+the accent of Christians, nor the gate of Christian, Pagan,
+or Norman, haue so strutted and bellowed, that I haue
+thought some of Natures Iouerney-men had made men,
+and not made them well, they imitated Humanity so abhominably
+
+ Play. I hope we haue reform'd that indifferently with
+vs, Sir
+
+ Ham. O reforme it altogether. And let those that
+play your Clownes, speake no more then is set downe for
+them. For there be of them, that will themselues laugh,
+to set on some quantitie of barren Spectators to laugh
+too, though in the meane time, some necessary Question
+of the Play be then to be considered: that's Villanous, &
+shewes a most pittifull Ambition in the Foole that vses
+it. Go make you readie.
+
+Exit Players.
+
+Enter Polonius, Rosincrance, and Guildensterne.
+
+How now my Lord,
+Will the King heare this peece of Worke?
+ Pol. And the Queene too, and that presently
+
+ Ham. Bid the Players make hast.
+
+Exit Polonius.
+
+Will you two helpe to hasten them?
+ Both. We will my Lord.
+
+Exeunt.
+
+Enter Horatio.
+
+ Ham. What hoa, Horatio?
+ Hora. Heere sweet Lord, at your Seruice
+
+ Ham. Horatio, thou art eene as iust a man
+As ere my Conuersation coap'd withall
+
+ Hora. O my deere Lord
+
+ Ham. Nay, do not thinke I flatter:
+For what aduancement may I hope from thee,
+That no Reuennew hast, but thy good spirits
+To feed & cloath thee. Why shold the poor be flatter'd?
+No, let the Candied tongue, like absurd pompe,
+And crooke the pregnant Hindges of the knee,
+Where thrift may follow faining? Dost thou heare,
+Since my deere Soule was Mistris of my choyse,
+And could of men distinguish, her election
+Hath seal'd thee for her selfe. For thou hast bene
+As one in suffering all, that suffers nothing.
+A man that Fortunes buffets, and Rewards
+Hath 'tane with equall Thankes. And blest are those,
+Whose Blood and Iudgement are so well co-mingled,
+That they are not a Pipe for Fortunes finger.
+To sound what stop she please. Giue me that man,
+That is not Passions Slaue, and I will weare him
+In my hearts Core. I, in my Heart of heart,
+As I do thee. Something too much of this.
+There is a Play to night to before the King.
+One Scoene of it comes neere the Circumstance
+Which I haue told thee, of my Fathers death.
+I prythee, when thou see'st that Acte a-foot,
+Euen with the verie Comment of my Soule
+Obserue mine Vnkle: If his occulted guilt,
+Do not it selfe vnkennell in one speech,
+It is a damned Ghost that we haue seene:
+And my Imaginations are as foule
+As Vulcans Stythe. Giue him needfull note,
+For I mine eyes will riuet to his Face:
+And after we will both our iudgements ioyne,
+To censure of his seeming
+
+ Hora. Well my Lord.
+If he steale ought the whil'st this Play is Playing,
+And scape detecting, I will pay the Theft.
+Enter King, Queene, Polonius, Ophelia, Rosincrance,
+Guildensterne, and
+other Lords attendant with his Guard carrying Torches. Danish
+March. Sound
+a Flourish.
+
+ Ham. They are comming to the Play: I must be idle.
+Get you a place
+
+ King. How fares our Cosin Hamlet?
+ Ham. Excellent Ifaith, of the Camelions dish: I eate
+the Ayre promise-cramm'd, you cannot feed Capons so
+
+ King. I haue nothing with this answer Hamlet, these
+words are not mine
+
+ Ham. No, nor mine. Now my Lord, you plaid once
+i'th' Vniuersity, you say?
+ Polon. That I did my Lord, and was accounted a good
+Actor
+
+ Ham. And what did you enact?
+ Pol. I did enact Iulius Caesar, I was kill'd i'th' Capitol:
+Brutus kill'd me
+
+ Ham. It was a bruite part of him, to kill so Capitall a
+Calfe there. Be the Players ready?
+ Rosin. I my Lord, they stay vpon your patience
+
+ Qu. Come hither my good Hamlet, sit by me
+
+ Ha. No good Mother, here's Mettle more attractiue
+
+ Pol. Oh ho, do you marke that?
+ Ham. Ladie, shall I lye in your Lap?
+ Ophe. No my Lord
+
+ Ham. I meane, my Head vpon your Lap?
+ Ophe. I my Lord
+
+ Ham. Do you thinke I meant Country matters?
+ Ophe. I thinke nothing, my Lord
+
+ Ham. That's a faire thought to ly betweene Maids legs
+ Ophe. What is my Lord?
+ Ham. Nothing
+
+ Ophe. You are merrie, my Lord?
+ Ham. Who I?
+ Ophe. I my Lord
+
+ Ham. Oh God, your onely Iigge-maker: what should
+a man do, but be merrie. For looke you how cheerefully
+my Mother lookes, and my Father dyed within's two
+Houres
+
+ Ophe. Nay, 'tis twice two moneths, my Lord
+
+ Ham. So long? Nay then let the Diuel weare blacke,
+for Ile haue a suite of Sables. Oh Heauens! dye two moneths
+ago, and not forgotten yet? Then there's hope, a
+great mans Memorie, may out-liue his life halfe a yeare:
+But byrlady he must builde Churches then: or else shall
+he suffer not thinking on, with the Hoby-horsse, whose
+Epitaph is, For o, For o, the Hoby-horse is forgot.
+
+Hoboyes play. The dumbe shew enters.
+
+Enter a King and Queene, very louingly; the Queene embracing
+him. She
+kneeles, and makes shew of Protestation vnto him. He takes her
+vp, and
+declines his head vpon her neck. Layes him downe vpon a Banke
+of Flowers.
+She seeing him a-sleepe, leaues him. Anon comes in a Fellow,
+takes off his
+Crowne, kisses it, and powres poyson in the Kings eares, and
+Exits. The
+Queene returnes, findes the King dead, and makes passionate
+Action. The
+Poysoner, with some two or three Mutes comes in againe, seeming
+to lament
+with her. The dead body is carried away: The Poysoner Wooes the
+Queene with
+Gifts, she seemes loath and vnwilling awhile, but in the end,
+accepts his
+loue.
+
+Exeunt.
+
+ Ophe. What meanes this, my Lord?
+ Ham. Marry this is Miching Malicho, that meanes
+Mischeefe
+
+ Ophe. Belike this shew imports the Argument of the
+Play?
+ Ham. We shall know by these Fellowes: the Players
+cannot keepe counsell, they'l tell all
+
+ Ophe. Will they tell vs what this shew meant?
+ Ham. I, or any shew that you'l shew him. Bee not
+you asham'd to shew, hee'l not shame to tell you what it
+meanes
+
+ Ophe. You are naught, you are naught, Ile marke the
+Play.
+Enter Prologue.
+
+For vs, and for our Tragedie,
+Heere stooping to your Clemencie:
+We begge your hearing Patientlie
+
+ Ham. Is this a Prologue, or the Poesie of a Ring?
+ Ophe. 'Tis briefe my Lord
+
+ Ham. As Womans loue.
+Enter King and his Queene.
+
+ King. Full thirtie times hath Phoebus Cart gon round,
+Neptunes salt Wash, and Tellus Orbed ground:
+And thirtie dozen Moones with borrowed sheene,
+About the World haue times twelue thirties beene,
+Since loue our hearts, and Hymen did our hands
+Vnite comutuall, in most sacred Bands
+
+ Bap. So many iournies may the Sunne and Moone
+Make vs againe count o're, ere loue be done.
+But woe is me, you are so sicke of late,
+So farre from cheere, and from your former state,
+That I distrust you: yet though I distrust,
+Discomfort you (my Lord) it nothing must:
+For womens Feare and Loue, holds quantitie,
+In neither ought, or in extremity:
+Now what my loue is, proofe hath made you know,
+And as my Loue is siz'd, my Feare is so
+
+ King. Faith I must leaue thee Loue, and shortly too:
+My operant Powers my Functions leaue to do:
+And thou shalt liue in this faire world behinde,
+Honour'd, belou'd, and haply, one as kinde.
+For Husband shalt thou-
+ Bap. Oh confound the rest:
+Such Loue, must needs be Treason in my brest:
+In second Husband, let me be accurst,
+None wed the second, but who kill'd the first
+
+ Ham. Wormwood, Wormwood
+
+ Bapt. The instances that second Marriage moue,
+Are base respects of Thrift, but none of Loue.
+A second time, I kill my Husband dead,
+When second Husband kisses me in Bed
+
+ King. I do beleeue you. Think what now you speak:
+But what we do determine, oft we breake:
+Purpose is but the slaue to Memorie,
+Of violent Birth, but poore validitie:
+Which now like Fruite vnripe stickes on the Tree,
+But fall vnshaken, when they mellow bee.
+Most necessary 'tis, that we forget
+To pay our selues, what to our selues is debt:
+What to our selues in passion we propose,
+The passion ending, doth the purpose lose.
+The violence of other Greefe or Ioy,
+Their owne ennactors with themselues destroy:
+Where Ioy most Reuels, Greefe doth most lament;
+Greefe ioyes, Ioy greeues on slender accident.
+This world is not for aye, nor 'tis not strange
+That euen our Loues should with our Fortunes change.
+For 'tis a question left vs yet to proue,
+Whether Loue lead Fortune, or else Fortune Loue.
+The great man downe, you marke his fauourites flies,
+The poore aduanc'd, makes Friends of Enemies:
+And hitherto doth Loue on Fortune tend,
+For who not needs, shall neuer lacke a Frend:
+And who in want a hollow Friend doth try,
+Directly seasons him his Enemie.
+But orderly to end, where I begun,
+Our Willes and Fates do so contrary run,
+That our Deuices still are ouerthrowne,
+Our thoughts are ours, their ends none of our owne.
+So thinke thou wilt no second Husband wed.
+But die thy thoughts, when thy first Lord is dead
+
+ Bap. Nor Earth to giue me food, nor Heauen light,
+Sport and repose locke from me day and night:
+Each opposite that blankes the face of ioy,
+Meet what I would haue well, and it destroy:
+Both heere, and hence, pursue me lasting strife,
+If once a Widdow, euer I be Wife
+
+ Ham. If she should breake it now
+
+ King. 'Tis deepely sworne:
+Sweet, leaue me heere a while,
+My spirits grow dull, and faine I would beguile
+The tedious day with sleepe
+
+ Qu. Sleepe rocke thy Braine,
+
+Sleepes
+
+And neuer come mischance betweene vs twaine.
+
+Exit
+
+ Ham. Madam, how like you this Play?
+ Qu. The Lady protests to much me thinkes
+
+ Ham. Oh but shee'l keepe her word
+
+ King. Haue you heard the Argument, is there no Offence
+in't?
+ Ham. No, no, they do but iest, poyson in iest, no Offence
+i'th' world
+
+ King. What do you call the Play?
+ Ham. The Mouse-trap: Marry how? Tropically:
+This Play is the Image of a murder done in Vienna: Gonzago
+is the Dukes name, his wife Baptista: you shall see
+anon: 'tis a knauish peece of worke: But what o'that?
+Your Maiestie, and wee that haue free soules, it touches
+vs not: let the gall'd iade winch: our withers are vnrung.
+Enter Lucianus.
+
+This is one Lucianus nephew to the King
+
+ Ophe. You are a good Chorus, my Lord
+
+ Ham. I could interpret betweene you and your loue:
+if I could see the Puppets dallying
+
+ Ophe. You are keene my Lord, you are keene
+
+ Ham. It would cost you a groaning, to take off my
+edge
+
+ Ophe. Still better and worse
+
+ Ham. So you mistake Husbands.
+Begin Murderer. Pox, leaue thy damnable Faces, and
+begin. Come, the croaking Rauen doth bellow for Reuenge
+
+ Lucian. Thoughts blacke, hands apt,
+Drugges fit, and Time agreeing:
+Confederate season, else, no Creature seeing:
+Thou mixture ranke, of Midnight Weeds collected,
+With Hecats Ban, thrice blasted, thrice infected,
+Thy naturall Magicke, and dire propertie,
+On wholsome life, vsurpe immediately.
+
+Powres the poyson in his eares.
+
+ Ham. He poysons him i'th' Garden for's estate: His
+name's Gonzago: the Story is extant and writ in choyce
+Italian. You shall see anon how the Murtherer gets the
+loue of Gonzago's wife
+
+ Ophe. The King rises
+
+ Ham. What, frighted with false fire
+
+ Qu. How fares my Lord?
+ Pol. Giue o're the Play
+
+ King. Giue me some Light. Away
+
+ All. Lights, Lights, Lights.
+
+Exeunt.
+
+Manet Hamlet & Horatio.
+
+ Ham. Why let the strucken Deere go weepe,
+The Hart vngalled play:
+For some must watch, while some must sleepe;
+So runnes the world away.
+Would not this Sir, and a Forrest of Feathers, if the rest of
+my Fortunes turne Turke with me; with two Prouinciall
+Roses on my rac'd Shooes, get me a Fellowship in a crie
+of Players sir
+
+ Hor. Halfe a share
+
+ Ham. A whole one I,
+For thou dost know: Oh Damon deere,
+This Realme dismantled was of Ioue himselfe,
+And now reignes heere.
+A verie verie Paiocke
+
+ Hora. You might haue Rim'd
+
+ Ham. Oh good Horatio, Ile take the Ghosts word for
+a thousand pound. Did'st perceiue?
+ Hora. Verie well my Lord
+
+ Ham. Vpon the talke of the poysoning?
+ Hora. I did verie well note him.
+Enter Rosincrance and Guildensterne.
+
+ Ham. Oh, ha? Come some Musick. Come y Recorders:
+For if the King like not the Comedie,
+Why then belike he likes it not perdie.
+Come some Musicke
+
+ Guild. Good my Lord, vouchsafe me a word with you
+
+ Ham. Sir, a whole History
+
+ Guild. The King, sir
+
+ Ham. I sir, what of him?
+ Guild. Is in his retyrement, maruellous distemper'd
+
+ Ham. With drinke Sir?
+ Guild. No my Lord, rather with choller
+
+ Ham. Your wisedome should shew it selfe more richer,
+to signifie this to his Doctor: for for me to put him
+to his Purgation, would perhaps plundge him into farre
+more Choller
+
+ Guild. Good my Lord put your discourse into some
+frame, and start not so wildely from my affayre
+
+ Ham. I am tame Sir, pronounce
+
+ Guild. The Queene your Mother, in most great affliction
+of spirit, hath sent me to you
+
+ Ham. You are welcome
+
+ Guild. Nay, good my Lord, this courtesie is not of
+the right breed. If it shall please you to make me a wholsome
+answer, I will doe your Mothers command'ment:
+if not, your pardon, and my returne shall bee the end of
+my Businesse
+
+ Ham. Sir, I cannot
+
+ Guild. What, my Lord?
+ Ham. Make you a wholsome answere: my wits diseas'd.
+But sir, such answers as I can make, you shal command:
+or rather you say, my Mother: therfore no more
+but to the matter. My Mother you say
+
+ Rosin. Then thus she sayes: your behauior hath stroke
+her into amazement, and admiration
+
+ Ham. Oh wonderfull Sonne, that can so astonish a
+Mother. But is there no sequell at the heeles of this Mothers
+admiration?
+ Rosin. She desires to speake with you in her Closset,
+ere you go to bed
+
+ Ham. We shall obey, were she ten times our Mother.
+Haue you any further Trade with vs?
+ Rosin. My Lord, you once did loue me
+
+ Ham. So I do still, by these pickers and stealers
+
+ Rosin. Good my Lord, what is your cause of distemper?
+You do freely barre the doore of your owne Libertie,
+if you deny your greefes to your Friend
+
+ Ham. Sir I lacke Aduancement
+
+ Rosin. How can that be, when you haue the voyce of
+the King himselfe, for your Succession in Denmarke?
+ Ham. I, but while the grasse growes, the Prouerbe is
+something musty.
+Enter one with a Recorder.
+
+O the Recorder. Let me see, to withdraw with you, why
+do you go about to recouer the winde of mee, as if you
+would driue me into a toyle?
+ Guild. O my Lord, if my Dutie be too bold, my loue
+is too vnmannerly
+
+ Ham. I do not well vnderstand that. Will you play
+vpon this Pipe?
+ Guild. My Lord, I cannot
+
+ Ham. I pray you
+
+ Guild. Beleeue me, I cannot
+
+ Ham. I do beseech you
+
+ Guild. I know no touch of it, my Lord
+
+ Ham. 'Tis as easie as lying: gouerne these Ventiges
+with your finger and thumbe, giue it breath with your
+mouth, and it will discourse most excellent Musicke.
+Looke you, these are the stoppes
+
+ Guild. But these cannot I command to any vtterance
+of hermony, I haue not the skill
+
+ Ham. Why looke you now, how vnworthy a thing
+you make of me: you would play vpon mee; you would
+seeme to know my stops: you would pluck out the heart
+of my Mysterie; you would sound mee from my lowest
+Note, to the top of my Compasse: and there is much Musicke,
+excellent Voice, in this little Organe, yet cannot
+you make it. Why do you thinke, that I am easier to bee
+plaid on, then a Pipe? Call me what Instrument you will,
+though you can fret me, you cannot play vpon me. God
+blesse you Sir.
+Enter Polonius.
+
+ Polon. My Lord; the Queene would speak with you,
+and presently
+
+ Ham. Do you see that Clowd? that's almost in shape
+like a Camell
+
+ Polon. By'th' Masse, and it's like a Camell indeed
+
+ Ham. Me thinkes it is like a Weazell
+
+ Polon. It is back'd like a Weazell
+
+ Ham. Or like a Whale?
+ Polon. Verie like a Whale
+
+ Ham. Then will I come to my Mother, by and by:
+They foole me to the top of my bent.
+I will come by and by
+
+ Polon. I will say so.
+Enter.
+
+ Ham. By and by, is easily said. Leaue me Friends:
+'Tis now the verie witching time of night,
+When Churchyards yawne, and Hell it selfe breaths out
+Contagion to this world. Now could I drink hot blood,
+And do such bitter businesse as the day
+Would quake to looke on. Soft now, to my Mother:
+Oh Heart, loose not thy Nature; let not euer
+The Soule of Nero, enter this firme bosome:
+Let me be cruell, not vnnaturall,
+I will speake Daggers to her, but vse none:
+My Tongue and Soule in this be Hypocrites.
+How in my words someuer she be shent,
+To giue them Seales, neuer my Soule consent.
+Enter King, Rosincrance, and Guildensterne.
+
+ King. I like him not, nor stands it safe with vs,
+To let his madnesse range. Therefore prepare you,
+I your Commission will forthwith dispatch,
+And he to England shall along with you:
+The termes of our estate, may not endure
+Hazard so dangerous as doth hourely grow
+Out of his Lunacies
+
+ Guild. We will our selues prouide:
+Most holie and Religious feare it is
+To keepe those many many bodies safe
+That liue and feede vpon your Maiestie
+
+ Rosin. The single
+And peculiar life is bound
+With all the strength and Armour of the minde,
+To keepe it selfe from noyance: but much more,
+That Spirit, vpon whose spirit depends and rests
+The liues of many, the cease of Maiestie
+Dies not alone; but like a Gulfe doth draw
+What's neere it, with it. It is a massie wheele
+Fixt on the Somnet of the highest Mount.
+To whose huge Spoakes, ten thousand lesser things
+Are mortiz'd and adioyn'd: which when it falles,
+Each small annexment, pettie consequence
+Attends the boystrous Ruine. Neuer alone
+Did the King sighe, but with a generall grone
+
+ King. Arme you, I pray you to this speedie Voyage;
+For we will Fetters put vpon this feare,
+Which now goes too free-footed
+
+ Both. We will haste vs.
+
+Exeunt. Gent.
+
+Enter Polonius.
+
+ Pol. My Lord, he's going to his Mothers Closset:
+Behinde the Arras Ile conuey my selfe
+To heare the Processe. Ile warrant shee'l tax him home,
+And as you said, and wisely was it said,
+'Tis meete that some more audience then a Mother,
+Since Nature makes them partiall, should o're-heare
+The speech of vantage. Fare you well my Liege,
+Ile call vpon you ere you go to bed,
+And tell you what I know
+
+ King. Thankes deere my Lord.
+Oh my offence is ranke, it smels to heauen,
+It hath the primall eldest curse vpon't,
+A Brothers murther. Pray can I not,
+Though inclination be as sharpe as will:
+My stronger guilt, defeats my strong intent,
+And like a man to double businesse bound,
+I stand in pause where I shall first begin,
+And both neglect; what if this cursed hand
+Were thicker then it selfe with Brothers blood,
+Is there not Raine enough in the sweet Heauens
+To wash it white as Snow? Whereto serues mercy,
+But to confront the visage of Offence?
+And what's in Prayer, but this two-fold force,
+To be fore-stalled ere we come to fall,
+Or pardon'd being downe? Then Ile looke vp,
+My fault is past. But oh, what forme of Prayer
+Can serue my turne? Forgiue me my foule Murther:
+That cannot be, since I am still possest
+Of those effects for which I did the Murther.
+My Crowne, mine owne Ambition, and my Queene:
+May one be pardon'd, and retaine th' offence?
+In the corrupted currants of this world,
+Offences gilded hand may shoue by Iustice,
+And oft 'tis seene, the wicked prize it selfe
+Buyes out the Law; but 'tis not so aboue,
+There is no shuffling, there the Action lyes
+In his true Nature, and we our selues compell'd
+Euen to the teeth and forehead of our faults,
+To giue in euidence. What then? What rests?
+Try what Repentance can. What can it not?
+Yet what can it, when one cannot repent?
+Oh wretched state! Oh bosome, blacke as death!
+Oh limed soule, that strugling to be free,
+Art more ingag'd: Helpe Angels, make assay:
+Bow stubborne knees, and heart with strings of Steele,
+Be soft as sinewes of the new-borne Babe,
+All may be well.
+Enter Hamlet.
+
+ Ham. Now might I do it pat, now he is praying,
+And now Ile doo't, and so he goes to Heauen,
+And so am I reueng'd: that would be scann'd,
+A Villaine killes my Father, and for that
+I his foule Sonne, do this same Villaine send
+To heauen. Oh this is hyre and Sallery, not Reuenge.
+He tooke my Father grossely, full of bread,
+With all his Crimes broad blowne, as fresh as May,
+And how his Audit stands, who knowes, saue Heauen:
+But in our circumstance and course of thought
+'Tis heauie with him: and am I then reueng'd,
+To take him in the purging of his Soule,
+When he is fit and season'd for his passage? No.
+Vp Sword, and know thou a more horrid hent
+When he is drunke asleepe: or in his Rage,
+Or in th' incestuous pleasure of his bed,
+At gaming, swearing, or about some acte
+That ha's no rellish of Saluation in't,
+Then trip him, that his heeles may kicke at Heauen,
+And that his Soule may be as damn'd and blacke
+As Hell, whereto it goes. My Mother stayes,
+This Physicke but prolongs thy sickly dayes.
+Enter.
+
+ King. My words flye vp, my thoughts remain below,
+Words without thoughts, neuer to Heauen go.
+Enter.
+
+Enter Queene and Polonius.
+
+ Pol. He will come straight:
+Looke you lay home to him,
+Tell him his prankes haue been too broad to beare with,
+And that your Grace hath screen'd, and stoode betweene
+Much heate, and him. Ile silence me e'ene heere:
+Pray you be round with him
+
+ Ham. within. Mother, mother, mother
+
+ Qu. Ile warrant you, feare me not.
+Withdraw, I heare him coming.
+Enter Hamlet.
+
+ Ham. Now Mother, what's the matter?
+ Qu. Hamlet, thou hast thy Father much offended
+
+
+ Ham. Mother, you haue my Father much offended
+
+ Qu. Come, come, you answer with an idle tongue
+
+ Ham. Go, go, you question with an idle tongue
+
+ Qu. Why how now Hamlet?
+ Ham. Whats the matter now?
+ Qu. Haue you forgot me?
+ Ham. No by the Rood, not so:
+You are the Queene, your Husbands Brothers wife,
+But would you were not so. You are my Mother
+
+ Qu. Nay, then Ile set those to you that can speake
+
+ Ham. Come, come, and sit you downe, you shall not
+boudge:
+You go not till I set you vp a glasse,
+Where you may see the inmost part of you?
+ Qu. What wilt thou do? thou wilt not murther me?
+Helpe, helpe, hoa
+
+ Pol. What hoa, helpe, helpe, helpe
+
+ Ham. How now, a Rat? dead for a Ducate, dead
+
+ Pol. Oh I am slaine.
+
+Killes Polonius
+
+ Qu. Oh me, what hast thou done?
+ Ham. Nay I know not, is it the King?
+ Qu. Oh what a rash, and bloody deed is this?
+ Ham. A bloody deed, almost as bad good Mother,
+As kill a King, and marrie with his Brother
+
+ Qu. As kill a King?
+ Ham. I Lady, 'twas my word.
+Thou wretched, rash, intruding foole farewell,
+I tooke thee for thy Betters, take thy Fortune,
+Thou find'st to be too busie, is some danger.
+Leaue wringing of your hands, peace, sit you downe,
+And let me wring your heart, for so I shall
+If it be made of penetrable stuffe;
+If damned Custome haue not braz'd it so,
+That it is proofe and bulwarke against Sense
+
+ Qu. What haue I done, that thou dar'st wag thy tong,
+In noise so rude against me?
+ Ham. Such an Act
+That blurres the grace and blush of Modestie,
+Cals Vertue Hypocrite, takes off the Rose
+From the faire forehead of an innocent loue,
+And makes a blister there. Makes marriage vowes
+As false as Dicers Oathes. Oh such a deed,
+As from the body of Contraction pluckes
+The very soule, and sweete Religion makes
+A rapsidie of words. Heauens face doth glow,
+Yea this solidity and compound masse,
+With tristfull visage as against the doome,
+Is thought-sicke at the act
+
+ Qu. Aye me; what act, that roares so lowd, & thunders
+in the Index
+
+ Ham. Looke heere vpon this Picture, and on this,
+The counterfet presentment of two Brothers:
+See what a grace was seated on his Brow,
+Hyperions curles, the front of Ioue himselfe,
+An eye like Mars, to threaten or command
+A Station, like the Herald Mercurie
+New lighted on a heauen-kissing hill:
+A Combination, and a forme indeed,
+Where euery God did seeme to set his Seale,
+To giue the world assurance of a man.
+This was your Husband. Looke you now what followes.
+Heere is your Husband, like a Mildew'd eare
+Blasting his wholsom breath. Haue you eyes?
+Could you on this faire Mountaine leaue to feed,
+And batten on this Moore? Ha? Haue you eyes?
+You cannot call it Loue: For at your age,
+The hey-day in the blood is tame, it's humble,
+And waites vpon the Iudgement: and what Iudgement
+Would step from this, to this? What diuell was't,
+That thus hath cousend you at hoodman-blinde?
+O Shame! where is thy Blush? Rebellious Hell,
+If thou canst mutine in a Matrons bones,
+To flaming youth, let Vertue be as waxe.
+And melt in her owne fire. Proclaime no shame,
+When the compulsiue Ardure giues the charge,
+Since Frost it selfe, as actiuely doth burne,
+As Reason panders Will
+
+ Qu. O Hamlet, speake no more.
+Thou turn'st mine eyes into my very soule,
+And there I see such blacke and grained spots,
+As will not leaue their Tinct
+
+ Ham. Nay, but to liue
+In the ranke sweat of an enseamed bed,
+Stew'd in Corruption; honying and making loue
+Ouer the nasty Stye
+
+ Qu. Oh speake to me, no more,
+These words like Daggers enter in mine eares.
+No more sweet Hamlet
+
+ Ham. A Murderer, and a Villaine:
+A Slaue, that is not twentieth part the tythe
+Of your precedent Lord. A vice of Kings,
+A Cutpurse of the Empire and the Rule.
+That from a shelfe, the precious Diadem stole,
+And put it in his Pocket
+
+ Qu. No more.
+Enter Ghost.
+
+ Ham. A King of shreds and patches.
+Saue me; and houer o're me with your wings
+You heauenly Guards. What would your gracious figure?
+ Qu. Alas he's mad
+
+ Ham. Do you not come your tardy Sonne to chide,
+That laps't in Time and Passion, lets go by
+Th' important acting of your dread command? Oh say
+
+ Ghost. Do not forget: this Visitation
+Is but to whet thy almost blunted purpose.
+But looke, Amazement on thy Mother sits;
+O step betweene her, and her fighting Soule,
+Conceit in weakest bodies, strongest workes.
+Speake to her Hamlet
+
+ Ham. How is it with you Lady?
+ Qu. Alas, how is't with you?
+That you bend your eye on vacancie,
+And with their corporall ayre do hold discourse.
+Forth at your eyes, your spirits wildely peepe,
+And as the sleeping Soldiours in th' Alarme,
+Your bedded haire, like life in excrements,
+Start vp, and stand an end. Oh gentle Sonne,
+Vpon the heate and flame of thy distemper
+Sprinkle coole patience. Whereon do you looke?
+ Ham. On him, on him: look you how pale he glares,
+His forme and cause conioyn'd, preaching to stones,
+Would make them capeable. Do not looke vpon me,
+Least with this pitteous action you conuert
+My sterne effects: then what I haue to do,
+Will want true colour; teares perchance for blood
+
+ Qu. To who do you speake this?
+ Ham. Do you see nothing there?
+ Qu. Nothing at all, yet all that is I see
+
+ Ham. Nor did you nothing heare?
+ Qu. No, nothing but our selues
+
+ Ham. Why look you there: looke how it steals away:
+My Father in his habite, as he liued,
+Looke where he goes euen now out at the Portall.
+Enter.
+
+ Qu. This is the very coynage of your Braine,
+This bodilesse Creation extasie is very cunning in
+
+ Ham. Extasie?
+My Pulse as yours doth temperately keepe time,
+And makes as healthfull Musicke. It is not madnesse
+That I haue vttered; bring me to the Test
+And I the matter will re-word: which madnesse
+Would gamboll from. Mother, for loue of Grace,
+Lay not a flattering Vnction to your soule,
+That not your trespasse, but my madnesse speakes:
+It will but skin and filme the Vlcerous place,
+Whil'st ranke Corruption mining all within,
+Infects vnseene. Confesse your selfe to Heauen,
+Repent what's past, auoyd what is to come,
+And do not spred the Compost on the Weedes,
+To make them ranke. Forgiue me this my Vertue,
+For in the fatnesse of this pursie times,
+Vertue it selfe, of Vice must pardon begge,
+Yea courb, and woe, for leaue to do him good
+
+ Qu. Oh Hamlet,
+Thou hast cleft my heart in twaine
+
+ Ham. O throw away the worser part of it,
+And liue the purer with the other halfe.
+Good night, but go not to mine Vnkles bed,
+Assume a Vertue, if you haue it not, refraine to night,
+And that shall lend a kinde of easinesse
+To the next abstinence. Once more goodnight,
+And when you are desirous to be blest,
+Ile blessing begge of you. For this same Lord,
+I do repent: but heauen hath pleas'd it so,
+To punish me with this, and this with me,
+That I must be their Scourge and Minister.
+I will bestow him, and will answer well
+The death I gaue him: so againe, good night.
+I must be cruell, onely to be kinde;
+Thus bad begins and worse remaines behinde
+
+ Qu. What shall I do?
+ Ham. Not this by no meanes that I bid you do:
+Let the blunt King tempt you againe to bed,
+Pinch Wanton on your cheeke, call you his Mouse,
+And let him for a paire of reechie kisses,
+Or padling in your necke with his damn'd Fingers,
+Make you to rauell all this matter out,
+That I essentially am not in madnesse,
+But made in craft. 'Twere good you let him know,
+For who that's but a Queene, faire, sober, wise,
+Would from a Paddocke, from a Bat, a Gibbe,
+Such deere concernings hide, Who would do so,
+No in despight of Sense and Secrecie,
+Vnpegge the Basket on the houses top:
+Let the Birds flye, and like the famous Ape
+To try Conclusions in the Basket, creepe
+And breake your owne necke downe
+
+ Qu. Be thou assur'd, if words be made of breath,
+And breath of life: I haue no life to breath
+What thou hast saide to me
+
+ Ham. I must to England, you know that?
+ Qu. Alacke I had forgot: 'Tis so concluded on
+
+ Ham. This man shall set me packing:
+Ile lugge the Guts into the Neighbor roome,
+Mother goodnight. Indeede this Counsellor
+Is now most still, most secret, and most graue,
+Who was in life, a foolish prating Knaue.
+Come sir, to draw toward an end with you.
+Good night Mother.
+Exit Hamlet tugging in Polonius.
+
+Enter King.
+
+ King. There's matters in these sighes.
+These profound heaues
+You must translate; Tis fit we vnderstand them.
+Where is your Sonne?
+ Qu. Ah my good Lord, what haue I seene to night?
+ King. What Gertrude? How do's Hamlet?
+ Qu. Mad as the Seas, and winde, when both contend
+Which is the Mightier, in his lawlesse fit
+Behinde the Arras, hearing something stirre,
+He whips his Rapier out, and cries a Rat, a Rat,
+And in his brainish apprehension killes
+The vnseene good old man
+
+ King. Oh heauy deed:
+It had bin so with vs had we beene there:
+His Liberty is full of threats to all,
+To you your selfe, to vs, to euery one.
+Alas, how shall this bloody deede be answered?
+It will be laide to vs, whose prouidence
+Should haue kept short, restrain'd, and out of haunt,
+This mad yong man. But so much was our loue,
+We would not vnderstand what was most fit,
+But like the Owner of a foule disease,
+To keepe it from divulging, let's it feede
+Euen on the pith of life. Where is he gone?
+ Qu. To draw apart the body he hath kild,
+O're whom his very madnesse like some Oare
+Among a Minerall of Mettels base
+Shewes it selfe pure. He weepes for what is done
+
+ King. Oh Gertrude, come away:
+The Sun no sooner shall the Mountaines touch,
+But we will ship him hence, and this vilde deed,
+We must with all our Maiesty and Skill
+Both countenance, and excuse.
+Enter Ros. & Guild.
+
+Ho Guildenstern:
+Friends both go ioyne you with some further ayde:
+Hamlet in madnesse hath Polonius slaine,
+And from his Mother Clossets hath he drag'd him.
+Go seeke him out, speake faire, and bring the body
+Into the Chappell. I pray you hast in this.
+Exit Gent.
+
+Come Gertrude, wee'l call vp our wisest friends,
+To let them know both what we meane to do,
+And what's vntimely done. Oh come away,
+My soule is full of discord and dismay.
+
+Exeunt.
+
+Enter Hamlet.
+
+ Ham. Safely stowed
+
+ Gentlemen within. Hamlet, Lord Hamlet
+
+ Ham. What noise? Who cals on Hamlet?
+Oh heere they come.
+Enter Ros. and Guildensterne.
+
+ Ro. What haue you done my Lord with the dead body?
+ Ham. Compounded it with dust, whereto 'tis Kinne
+
+ Rosin. Tell vs where 'tis, that we may take it thence,
+And beare it to the Chappell
+
+ Ham. Do not beleeue it
+
+ Rosin. Beleeue what?
+ Ham. That I can keepe your counsell, and not mine
+owne. Besides, to be demanded of a Spundge, what replication
+should be made by the Sonne of a King
+
+ Rosin. Take you me for a Spundge, my Lord?
+ Ham. I sir, that sokes vp the Kings Countenance, his
+Rewards, his Authorities (but such Officers do the King
+best seruice in the end. He keepes them like an Ape in
+the corner of his iaw, first mouth'd to be last swallowed,
+when he needes what you haue glean'd, it is but squeezing
+you, and Spundge you shall be dry againe
+
+ Rosin. I vnderstand you not my Lord
+
+ Ham. I am glad of it: a knauish speech sleepes in a
+foolish eare
+
+ Rosin. My Lord, you must tell vs where the body is,
+and go with vs to the King
+
+ Ham. The body is with the King, but the King is not
+with the body. The King, is a thing-
+ Guild. A thing my Lord?
+ Ham. Of nothing: bring me to him, hide Fox, and all
+after.
+
+Exeunt.
+
+Enter King.
+
+ King. I haue sent to seeke him, and to find the bodie:
+How dangerous is it that this man goes loose:
+Yet must not we put the strong Law on him:
+Hee's loued of the distracted multitude,
+Who like not in their iudgement, but their eyes:
+And where 'tis so, th' Offenders scourge is weigh'd
+But neerer the offence: to beare all smooth, and euen,
+This sodaine sending him away, must seeme
+Deliberate pause, diseases desperate growne,
+By desperate appliance are releeued,
+Or not at all.
+Enter Rosincrane.
+
+How now? What hath befalne?
+ Rosin. Where the dead body is bestow'd my Lord,
+We cannot get from him
+
+ King. But where is he?
+ Rosin. Without my Lord, guarded to know your
+pleasure
+
+ King. Bring him before vs
+
+ Rosin. Hoa, Guildensterne? Bring in my Lord.
+Enter Hamlet and Guildensterne.
+
+ King. Now Hamlet, where's Polonius?
+ Ham. At Supper
+
+ King. At Supper? Where?
+ Ham. Not where he eats, but where he is eaten, a certaine
+conuocation of wormes are e'ne at him. Your worm
+is your onely Emperor for diet. We fat all creatures else
+to fat vs, and we fat our selfe for Magots. Your fat King,
+and your leane Begger is but variable seruice to dishes,
+but to one Table that's the end
+
+ King. What dost thou meane by this?
+ Ham. Nothing but to shew you how a King may go
+a Progresse through the guts of a Begger
+
+ King. Where is Polonius
+
+ Ham. In heauen, send thither to see. If your Messenger
+finde him not there, seeke him i'th other place your
+selfe: but indeed, if you finde him not this moneth, you
+shall nose him as you go vp the staires into the Lobby
+
+ King. Go seeke him there
+
+ Ham. He will stay till ye come
+
+ K. Hamlet, this deed of thine, for thine especial safety
+Which we do tender, as we deerely greeue
+For that which thou hast done, must send thee hence
+With fierie Quicknesse. Therefore prepare thy selfe,
+The Barke is readie, and the winde at helpe,
+Th' Associates tend, and euery thing at bent
+For England
+
+ Ham. For England?
+ King. I Hamlet
+
+ Ham. Good
+
+ King. So is it, if thou knew'st our purposes
+
+ Ham. I see a Cherube that see's him: but come, for
+England. Farewell deere Mother
+
+ King. Thy louing Father Hamlet
+
+ Hamlet. My Mother: Father and Mother is man and
+wife: man & wife is one flesh, and so my mother. Come,
+for England.
+
+Exit
+
+ King. Follow him at foote,
+Tempt him with speed aboord:
+Delay it not, Ile haue him hence to night.
+Away, for euery thing is Seal'd and done
+That else leanes on th' Affaire, pray you make hast.
+And England, if my loue thou holdst at ought,
+As my great power thereof may giue thee sense,
+Since yet thy Cicatrice lookes raw and red
+After the Danish Sword, and thy free awe
+Payes homage to vs; thou maist not coldly set
+Our Soueraigne Processe, which imports at full
+By Letters coniuring to that effect
+The present death of Hamlet. Do it England,
+For like the Hecticke in my blood he rages,
+And thou must cure me: Till I know 'tis done,
+How ere my happes, my ioyes were ne're begun.
+
+Exit
+
+Enter Fortinbras with an Armie.
+
+ For. Go Captaine, from me greet the Danish King,
+Tell him that by his license, Fortinbras
+Claimes the conueyance of a promis'd March
+Ouer his Kingdome. You know the Rendeuous:
+If that his Maiesty would ought with vs,
+We shall expresse our dutie in his eye,
+And let him know so
+
+ Cap. I will doo't, my Lord
+
+ For. Go safely on.
+Enter.
+
+Enter Queene and Horatio.
+
+ Qu. I will not speake with her
+
+ Hor. She is importunate, indeed distract, her moode
+will needs be pittied
+
+ Qu. What would she haue?
+ Hor. She speakes much of her Father; saies she heares
+There's trickes i'th' world, and hems, and beats her heart,
+Spurnes enuiously at Strawes, speakes things in doubt,
+That carry but halfe sense: Her speech is nothing,
+Yet the vnshaped vse of it doth moue
+The hearers to Collection; they ayme at it,
+And botch the words vp fit to their owne thoughts,
+Which as her winkes, and nods, and gestures yeeld them,
+Indeed would make one thinke there would be thought,
+Though nothing sure, yet much vnhappily
+
+ Qu. 'Twere good she were spoken with,
+For she may strew dangerous coniectures
+In ill breeding minds. Let her come in.
+To my sicke soule (as sinnes true Nature is)
+Each toy seemes Prologue, to some great amisse,
+So full of Artlesse iealousie is guilt,
+It spill's it selfe, in fearing to be spilt.
+Enter Ophelia distracted.
+
+ Ophe. Where is the beauteous Maiesty of Denmark
+
+ Qu. How now Ophelia?
+ Ophe. How should I your true loue know from another one?
+By his Cockle hat and staffe, and his Sandal shoone
+
+ Qu. Alas sweet Lady: what imports this Song?
+ Ophe. Say you? Nay pray you marke.
+He is dead and gone Lady, he is dead and gone,
+At his head a grasse-greene Turfe, at his heeles a stone.
+Enter King.
+
+ Qu. Nay but Ophelia
+
+ Ophe. Pray you marke.
+White his Shrow'd as the Mountaine Snow
+
+ Qu. Alas, looke heere my Lord
+
+ Ophe. Larded with sweet Flowers:
+Which bewept to the graue did not go,
+With true-loue showres
+
+ King. How do ye, pretty Lady?
+ Ophe. Well, God dil'd you. They say the Owle was
+a Bakers daughter. Lord, wee know what we are, but
+know not what we may be. God be at your Table
+
+ King. Conceit vpon her Father
+
+ Ophe. Pray you let's haue no words of this: but when
+they aske you what it meanes, say you this:
+To morrow is S[aint]. Valentines day, all in the morning betime,
+And I a Maid at your Window, to be your Valentine.
+Then vp he rose, & don'd his clothes, & dupt the chamber dore,
+Let in the Maid, that out a Maid, neuer departed more
+
+ King. Pretty Ophelia
+
+ Ophe. Indeed la? without an oath Ile make an end ont.
+By gis, and by S[aint]. Charity,
+Alacke, and fie for shame:
+Yong men wil doo't, if they come too't,
+By Cocke they are too blame.
+Quoth she before you tumbled me,
+You promis'd me to Wed:
+So would I ha done by yonder Sunne,
+And thou hadst not come to my bed
+
+ King. How long hath she bin thus?
+ Ophe. I hope all will be well. We must bee patient,
+but I cannot choose but weepe, to thinke they should
+lay him i'th' cold ground: My brother shall knowe of it,
+and so I thanke you for your good counsell. Come, my
+Coach: Goodnight Ladies: Goodnight sweet Ladies:
+Goodnight, goodnight.
+Enter.
+
+ King. Follow her close,
+Giue her good watch I pray you:
+Oh this is the poyson of deepe greefe, it springs
+All from her Fathers death. Oh Gertrude, Gertrude,
+When sorrowes comes, they come not single spies,
+But in Battalians. First, her Father slaine,
+Next your Sonne gone, and he most violent Author
+Of his owne iust remoue: the people muddied,
+Thicke and vnwholsome in their thoughts, and whispers
+For good Polonius death; and we haue done but greenly
+In hugger mugger to interre him. Poore Ophelia
+Diuided from her selfe, and her faire Iudgement,
+Without the which we are Pictures, or meere Beasts.
+Last, and as much containing as all these,
+Her Brother is in secret come from France,
+Keepes on his wonder, keepes himselfe in clouds,
+And wants not Buzzers to infect his eare
+With pestilent Speeches of his Fathers death,
+Where in necessitie of matter Beggard,
+Will nothing sticke our persons to Arraigne
+In eare and eare. O my deere Gertrude, this,
+Like to a murdering Peece in many places,
+Giues me superfluous death.
+
+A Noise within.
+
+Enter a Messenger.
+
+ Qu. Alacke, what noyse is this?
+ King. Where are my Switzers?
+Let them guard the doore. What is the matter?
+ Mes. Saue your selfe, my Lord.
+The Ocean (ouer-peering of his List)
+Eates not the Flats with more impittious haste
+Then young Laertes, in a Riotous head,
+Ore-beares your Officers, the rabble call him Lord,
+And as the world were now but to begin,
+Antiquity forgot, Custome not knowne,
+The Ratifiers and props of euery word,
+They cry choose we? Laertes shall be King,
+Caps, hands, and tongues, applaud it to the clouds,
+Laertes shall be King, Laertes King
+
+ Qu. How cheerefully on the false Traile they cry,
+Oh this is Counter you false Danish Dogges.
+
+Noise within. Enter Laertes.
+
+ King. The doores are broke
+
+ Laer. Where is the King, sirs? Stand you all without
+
+ All. No, let's come in
+
+ Laer. I pray you giue me leaue
+
+ Al. We will, we will
+
+ Laer. I thanke you: Keepe the doore.
+Oh thou vilde King, giue me my Father
+
+ Qu. Calmely good Laertes
+
+ Laer. That drop of blood, that calmes
+Proclaimes me Bastard:
+Cries Cuckold to my Father, brands the Harlot
+Euen heere betweene the chaste vnsmirched brow
+Of my true Mother
+
+ King. What is the cause Laertes,
+That thy Rebellion lookes so Gyant-like?
+Let him go Gertrude: Do not feare our person:
+There's such Diuinity doth hedge a King,
+That Treason can but peepe to what it would,
+Acts little of his will. Tell me Laertes,
+Why thou art thus Incenst? Let him go Gertrude.
+Speake man
+
+ Laer. Where's my Father?
+ King. Dead
+
+ Qu. But not by him
+
+ King. Let him demand his fill
+
+ Laer. How came he dead? Ile not be Iuggel'd with.
+To hell Allegeance: Vowes, to the blackest diuell.
+Conscience and Grace, to the profoundest Pit.
+I dare Damnation: to this point I stand,
+That both the worlds I giue to negligence,
+Let come what comes: onely Ile be reueng'd
+Most throughly for my Father
+
+ King. Who shall stay you?
+ Laer. My Will, not all the world,
+And for my meanes, Ile husband them so well,
+They shall go farre with little
+
+ King. Good Laertes:
+If you desire to know the certaintie
+Of your deere Fathers death, if writ in your reuenge,
+That Soop-stake you will draw both Friend and Foe,
+Winner and Looser
+
+ Laer. None but his Enemies
+
+ King. Will you know them then
+
+ La. To his good Friends, thus wide Ile ope my Armes:
+And like the kinde Life-rend'ring Politician,
+Repast them with my blood
+
+ King. Why now you speake
+Like a good Childe, and a true Gentleman.
+That I am guiltlesse of your Fathers death,
+And am most sensible in greefe for it,
+It shall as leuell to your Iudgement pierce
+As day do's to your eye.
+
+A noise within. Let her come in.
+
+Enter Ophelia.
+
+ Laer. How now? what noise is that?
+Oh heate drie vp my Braines, teares seuen times salt,
+Burne out the Sence and Vertue of mine eye.
+By Heauen, thy madnesse shall be payed by waight,
+Till our Scale turnes the beame. Oh Rose of May,
+Deere Maid, kinde Sister, sweet Ophelia:
+Oh Heauens, is't possible, a yong Maids wits,
+Should be as mortall as an old mans life?
+Nature is fine in Loue, and where 'tis fine,
+It sends some precious instance of it selfe
+After the thing it loues
+
+ Ophe. They bore him bare fac'd on the Beer,
+Hey non nony, nony, hey nony:
+And on his graue raines many a teare,
+Fare you well my Doue
+
+ Laer. Had'st thou thy wits, and did'st perswade Reuenge,
+it could not moue thus
+
+ Ophe. You must sing downe a-downe, and you call
+him a-downe-a. Oh, how the wheele becomes it? It is
+the false Steward that stole his masters daughter
+
+ Laer. This nothings more then matter
+
+ Ophe. There's Rosemary, that's for Remembraunce.
+Pray loue remember: and there is Paconcies, that's for
+Thoughts
+
+ Laer. A document in madnesse, thoughts & remembrance
+fitted
+
+ Ophe. There's Fennell for you, and Columbines: ther's
+Rew for you, and heere's some for me. Wee may call it
+Herbe-Grace a Sundaies: Oh you must weare your Rew
+with a difference. There's a Daysie, I would giue you
+some Violets, but they wither'd all when my Father dyed:
+They say, he made a good end;
+For bonny sweet Robin is all my ioy
+
+ Laer. Thought, and Affliction, Passion, Hell it selfe:
+She turnes to Fauour, and to prettinesse
+
+ Ophe. And will he not come againe,
+And will he not come againe:
+No, no, he is dead, go to thy Death-bed,
+He neuer wil come againe.
+His Beard as white as Snow,
+All Flaxen was his Pole:
+He is gone, he is gone, and we cast away mone,
+Gramercy on his Soule.
+And of all Christian Soules, I pray God.
+God buy ye.
+
+Exeunt. Ophelia
+
+ Laer. Do you see this, you Gods?
+ King. Laertes, I must common with your greefe,
+Or you deny me right: go but apart,
+Make choice of whom your wisest Friends you will,
+And they shall heare and iudge 'twixt you and me;
+If by direct or by Colaterall hand
+They finde vs touch'd, we will our Kingdome giue,
+Our Crowne, our Life, and all that we call Ours
+To you in satisfaction. But if not,
+Be you content to lend your patience to vs,
+And we shall ioyntly labour with your soule
+To giue it due content
+
+ Laer. Let this be so:
+His meanes of death, his obscure buriall;
+No Trophee, Sword, nor Hatchment o're his bones,
+No Noble rite, nor formall ostentation,
+Cry to be heard, as 'twere from Heauen to Earth,
+That I must call in question
+
+ King. So you shall:
+And where th' offence is, let the great Axe fall.
+I pray you go with me.
+
+Exeunt.
+
+Enter Horatio, with an Attendant.
+
+ Hora. What are they that would speake with me?
+ Ser. Saylors sir, they say they haue Letters for you
+
+ Hor. Let them come in,
+I do not know from what part of the world
+I should be greeted, if not from Lord Hamlet.
+Enter Saylor.
+
+ Say. God blesse you Sir
+
+ Hor. Let him blesse thee too
+
+ Say. Hee shall Sir, and't please him. There's a Letter
+for you Sir: It comes from th' Ambassadours that was
+bound for England, if your name be Horatio, as I am let
+to know it is.
+
+Reads the Letter.
+
+Horatio, When thou shalt haue ouerlook'd this, giue these
+Fellowes some meanes to the King: They haue Letters
+for him. Ere we were two dayes old at Sea, a Pyrate of very
+Warlicke appointment gaue vs Chace. Finding our selues too
+slow of Saile, we put on a compelled Valour. In the Grapple, I
+boorded them: On the instant they got cleare of our Shippe, so
+I alone became their Prisoner. They haue dealt with mee, like
+Theeues of Mercy, but they knew what they did. I am to doe
+a good turne for them. Let the King haue the Letters I haue
+sent, and repaire thou to me with as much hast as thou wouldest
+flye death. I haue words to speake in your eare, will make thee
+dumbe, yet are they much too light for the bore of the Matter.
+These good Fellowes will bring thee where I am. Rosincrance
+and Guildensterne, hold their course for England. Of them
+I haue much to tell thee, Farewell.
+He that thou knowest thine,
+Hamlet.
+Come, I will giue you way for these your Letters,
+And do't the speedier, that you may direct me
+To him from whom you brought them.
+Enter.
+
+Enter King and Laertes.
+
+ King. Now must your conscience my acquittance seal,
+And you must put me in your heart for Friend,
+Sith you haue heard, and with a knowing eare,
+That he which hath your Noble Father slaine,
+Pursued my life
+
+ Laer. It well appeares. But tell me,
+Why you proceeded not against these feates,
+So crimefull, and so Capitall in Nature,
+As by your Safety, Wisedome, all things else,
+You mainly were stirr'd vp?
+ King. O for two speciall Reasons,
+Which may to you (perhaps) seeme much vnsinnowed,
+And yet to me they are strong. The Queen his Mother,
+Liues almost by his lookes: and for my selfe,
+My Vertue or my Plague, be it either which,
+She's so coniunctiue to my life, and soule;
+That as the Starre moues not but in his Sphere,
+I could not but by her. The other Motiue,
+Why to a publike count I might not go,
+Is the great loue the generall gender beare him,
+Who dipping all his Faults in their affection,
+Would like the Spring that turneth Wood to Stone,
+Conuert his Gyues to Graces. So that my Arrowes
+Too slightly timbred for so loud a Winde,
+Would haue reuerted to my Bow againe,
+And not where I had arm'd them
+
+ Laer. And so haue I a Noble Father lost,
+A Sister driuen into desperate tearmes,
+Who was (if praises may go backe againe)
+Stood Challenger on mount of all the Age
+For her perfections. But my reuenge will come
+
+ King. Breake not your sleepes for that,
+You must not thinke
+That we are made of stuffe, so flat, and dull,
+That we can let our Beard be shooke with danger,
+And thinke it pastime. You shortly shall heare more,
+I lou'd your Father, and we loue our Selfe,
+And that I hope will teach you to imagine-
+Enter a Messenger.
+
+How now? What Newes?
+ Mes. Letters my Lord from Hamlet, This to your
+Maiesty: this to the Queene
+
+ King. From Hamlet? Who brought them?
+ Mes. Saylors my Lord they say, I saw them not:
+They were giuen me by Claudio, he receiu'd them
+
+ King. Laertes you shall heare them:
+Leaue vs.
+
+Exit Messenger
+
+High and Mighty, you shall know I am set naked on your
+Kingdome. To morrow shall I begge leaue to see your Kingly
+Eyes. When I shall (first asking your Pardon thereunto) recount
+th' Occasions of my sodaine, and more strange returne.
+Hamlet.
+What should this meane? Are all the rest come backe?
+Or is it some abuse? Or no such thing?
+ Laer. Know you the hand?
+ Kin. 'Tis Hamlets Character, naked and in a Postscript
+here he sayes alone: Can you aduise me?
+ Laer. I'm lost in it my Lord; but let him come,
+It warmes the very sicknesse in my heart,
+That I shall liue and tell him to his teeth;
+Thus diddest thou
+
+ Kin. If it be so Laertes, as how should it be so:
+How otherwise will you be rul'd by me?
+ Laer. If so you'l not o'rerule me to a peace
+
+ Kin. To thine owne peace: if he be now return'd,
+As checking at his Voyage, and that he meanes
+No more to vndertake it; I will worke him
+To an exployt now ripe in my Deuice,
+Vnder the which he shall not choose but fall;
+And for his death no winde of blame shall breath,
+But euen his Mother shall vncharge the practice,
+And call it accident: Some two Monthes hence
+Here was a Gentleman of Normandy,
+I'ue seene my selfe, and seru'd against the French,
+And they ran well on Horsebacke; but this Gallant
+Had witchcraft in't; he grew into his Seat,
+And to such wondrous doing brought his Horse,
+As had he beene encorps't and demy-Natur'd
+With the braue Beast, so farre he past my thought,
+That I in forgery of shapes and trickes,
+Come short of what he did
+
+ Laer. A Norman was't?
+ Kin. A Norman
+
+ Laer. Vpon my life Lamound
+
+ Kin. The very same
+
+ Laer. I know him well, he is the Brooch indeed,
+And Iemme of all our Nation
+
+ Kin. Hee mad confession of you,
+And gaue you such a Masterly report,
+For Art and exercise in your defence;
+And for your Rapier most especiall,
+That he cryed out, t'would be a sight indeed,
+If one could match you Sir. This report of his
+Did Hamlet so envenom with his Enuy,
+That he could nothing doe but wish and begge,
+Your sodaine comming ore to play with him;
+Now out of this
+
+ Laer. Why out of this, my Lord?
+ Kin. Laertes was your Father deare to you?
+Or are you like the painting of a sorrow,
+A face without a heart?
+ Laer. Why aske you this?
+ Kin. Not that I thinke you did not loue your Father,
+But that I know Loue is begun by Time:
+And that I see in passages of proofe,
+Time qualifies the sparke and fire of it:
+Hamlet comes backe: what would you vndertake,
+To show your selfe your Fathers sonne indeed,
+More then in words?
+ Laer. To cut his throat i'th' Church
+
+ Kin. No place indeed should murder Sancturize;
+Reuenge should haue no bounds: but good Laertes
+Will you doe this, keepe close within your Chamber,
+Hamlet return'd, shall know you are come home:
+Wee'l put on those shall praise your excellence,
+And set a double varnish on the fame
+The Frenchman gaue you, bring you in fine together,
+And wager on your heads, he being remisse,
+Most generous, and free from all contriuing,
+Will not peruse the Foiles? So that with ease,
+Or with a little shuffling, you may choose
+A Sword vnbaited, and in a passe of practice,
+Requit him for your Father
+
+ Laer. I will doo't.
+And for that purpose Ile annoint my Sword:
+I bought an Vnction of a Mountebanke
+So mortall, I but dipt a knife in it,
+Where it drawes blood, no Cataplasme so rare,
+Collected from all Simples that haue Vertue
+Vnder the Moone, can saue the thing from death,
+That is but scratcht withall: Ile touch my point,
+With this contagion, that if I gall him slightly,
+It may be death
+
+ Kin. Let's further thinke of this,
+Weigh what conuenience both of time and meanes
+May fit vs to our shape, if this should faile;
+And that our drift looke through our bad performance,
+'Twere better not assaid; therefore this Proiect
+Should haue a backe or second, that might hold,
+If this should blast in proofe: Soft, let me see
+Wee'l make a solemne wager on your commings,
+I ha't: when in your motion you are hot and dry,
+As make your bowts more violent to the end,
+And that he cals for drinke; Ile haue prepar'd him
+A Challice for the nonce; whereon but sipping,
+If he by chance escape your venom'd stuck,
+Our purpose may hold there; how sweet Queene.
+Enter Queene.
+
+ Queen. One woe doth tread vpon anothers heele,
+So fast they'l follow: your Sister's drown'd Laertes
+
+ Laer. Drown'd! O where?
+ Queen. There is a Willow growes aslant a Brooke,
+That shewes his hore leaues in the glassie streame:
+There with fantasticke Garlands did she come,
+Of Crow-flowers, Nettles, Daysies, and long Purples,
+That liberall Shepheards giue a grosser name;
+But our cold Maids doe Dead Mens Fingers call them:
+There on the pendant boughes, her Coronet weeds
+Clambring to hang; an enuious sliuer broke,
+When downe the weedy Trophies, and her selfe,
+Fell in the weeping Brooke, her cloathes spred wide,
+And Mermaid-like, a while they bore her vp,
+Which time she chaunted snatches of old tunes,
+As one incapable of her owne distresse,
+Or like a creature Natiue, and indued
+Vnto that Element: but long it could not be,
+Till that her garments, heauy with her drinke,
+Pul'd the poore wretch from her melodious buy,
+To muddy death
+
+ Laer. Alas then, is she drown'd?
+ Queen. Drown'd, drown'd
+
+ Laer. Too much of water hast thou poore Ophelia,
+And therefore I forbid my teares: but yet
+It is our tricke, Nature her custome holds,
+Let shame say what it will; when these are gone
+The woman will be out: Adue my Lord,
+I haue a speech of fire, that faine would blaze,
+But that this folly doubts it.
+Enter.
+
+ Kin. Let's follow, Gertrude:
+How much I had to doe to calme his rage?
+Now feare I this will giue it start againe;
+Therefore let's follow.
+
+Exeunt.
+
+Enter two Clownes.
+
+ Clown. Is she to bee buried in Christian buriall, that
+wilfully seekes her owne saluation?
+ Other. I tell thee she is, and therefore make her Graue
+straight, the Crowner hath sate on her, and finds it Christian
+buriall
+
+ Clo. How can that be, vnlesse she drowned her selfe in
+her owne defence?
+ Other. Why 'tis found so
+
+ Clo. It must be Se offendendo, it cannot bee else: for
+heere lies the point; If I drowne my selfe wittingly, it argues
+an Act: and an Act hath three branches. It is an
+Act to doe and to performe; argall she drown'd her selfe
+wittingly
+
+ Other. Nay but heare you Goodman Deluer
+
+ Clown. Giue me leaue; heere lies the water; good:
+heere stands the man; good: If the man goe to this water
+and drowne himselfe; it is will he nill he, he goes;
+marke you that? But if the water come to him & drowne
+him; hee drownes not himselfe. Argall, hee that is not
+guilty of his owne death, shortens not his owne life
+
+ Other. But is this law?
+ Clo. I marry is't, Crowners Quest Law
+
+ Other. Will you ha the truth on't: if this had not
+beene a Gentlewoman, shee should haue beene buried
+out of Christian Buriall
+
+ Clo. Why there thou say'st. And the more pitty that
+great folke should haue countenance in this world to
+drowne or hang themselues, more then their euen Christian.
+Come, my Spade; there is no ancient Gentlemen,
+but Gardiners, Ditchers and Graue-makers; they hold vp
+Adams Profession
+
+ Other. Was he a Gentleman?
+ Clo. He was the first that euer bore Armes
+
+ Other. Why he had none
+
+ Clo. What, ar't a Heathen? how doth thou vnderstand
+the Scripture? the Scripture sayes Adam dig'd;
+could hee digge without Armes? Ile put another question
+to thee; if thou answerest me not to the purpose, confesse
+thy selfe-
+ Other. Go too
+
+ Clo. What is he that builds stronger then either the
+Mason, the Shipwright, or the Carpenter?
+ Other. The Gallowes maker; for that Frame outliues a
+thousand Tenants
+
+ Clo. I like thy wit well in good faith, the Gallowes
+does well; but how does it well? it does well to those
+that doe ill: now, thou dost ill to say the Gallowes is
+built stronger then the Church: Argall, the Gallowes
+may doe well to thee. Too't againe, Come
+
+ Other. Who builds stronger then a Mason, a Shipwright,
+or a Carpenter?
+ Clo. I, tell me that, and vnyoake
+
+ Other. Marry, now I can tell
+
+ Clo. Too't
+
+ Other. Masse, I cannot tell.
+Enter Hamlet and Horatio a farre off.
+
+ Clo. Cudgell thy braines no more about it; for your
+dull Asse will not mend his pace with beating; and when
+you are ask't this question next, say a Graue-maker: the
+Houses that he makes, lasts till Doomesday: go, get thee
+to Yaughan, fetch me a stoupe of Liquor.
+
+Sings.
+
+In youth when I did loue, did loue,
+me thought it was very sweete:
+To contract O the time for a my behoue,
+O me thought there was nothing meete
+
+ Ham. Ha's this fellow no feeling of his businesse, that
+he sings at Graue-making?
+ Hor. Custome hath made it in him a property of easinesse
+
+ Ham. 'Tis ee'n so; the hand of little Imployment hath
+the daintier sense
+
+ Clowne sings. But Age with his stealing steps
+hath caught me in his clutch:
+And hath shipped me intill the Land,
+as if I had neuer beene such
+
+ Ham. That Scull had a tongue in it, and could sing
+once: how the knaue iowles it to th' grownd, as if it
+were Caines Iaw-bone, that did the first murther: It
+might be the Pate of a Polititian which this Asse o're Offices:
+one that could circumuent God, might it not?
+ Hor. It might, my Lord
+
+ Ham. Or of a Courtier, which could say, Good Morrow
+sweet Lord: how dost thou, good Lord? this
+might be my Lord such a one, that prais'd my Lord such
+a ones Horse, when he meant to begge it; might it not?
+ Hor. I, my Lord
+
+ Ham. Why ee'n so: and now my Lady Wormes,
+Chaplesse, and knockt about the Mazard with a Sextons
+Spade; heere's fine Reuolution, if wee had the tricke to
+see't. Did these bones cost no more the breeding, but
+to play at Loggets with 'em? mine ake to thinke
+on't
+
+ Clowne sings. A Pickhaxe and a Spade, a Spade,
+for and a shrowding-Sheete:
+O a Pit of Clay for to be made,
+for such a Guest is meete
+
+ Ham. There's another: why might not that bee the
+Scull of a Lawyer? where be his Quiddits now? his
+Quillets? his Cases? his Tenures, and his Tricks? why
+doe's he suffer this rude knaue now to knocke him about
+the Sconce with a dirty Shouell, and will not tell him of
+his Action of Battery? hum. This fellow might be in's
+time a great buyer of Land, with his Statutes, his Recognizances,
+his Fines, his double Vouchers, his Recoueries:
+Is this the fine of his Fines, and the recouery of his Recoueries,
+to haue his fine Pate full of fine Dirt? will his
+Vouchers vouch him no more of his Purchases, and double
+ones too, then the length and breadth of a paire of
+Indentures? the very Conueyances of his Lands will
+hardly lye in this Boxe; and must the Inheritor himselfe
+haue no more? ha?
+ Hor. Not a iot more, my Lord
+
+ Ham. Is not Parchment made of Sheep-skinnes?
+ Hor. I my Lord, and of Calue-skinnes too
+
+ Ham. They are Sheepe and Calues that seek out assurance
+in that. I will speake to this fellow: whose Graue's
+this Sir?
+ Clo. Mine Sir:
+O a Pit of Clay for to be made,
+for such a Guest is meete
+
+ Ham. I thinke it be thine indeed: for thou liest in't
+
+ Clo. You lye out on't Sir, and therefore it is not yours:
+for my part, I doe not lye in't; and yet it is mine
+
+ Ham. Thou dost lye in't, to be in't and say 'tis thine:
+'tis for the dead, not for the quicke, therefore thou
+lyest
+
+ Clo. 'Tis a quicke lye Sir, 'twill away againe from me
+to you
+
+ Ham. What man dost thou digge it for?
+ Clo. For no man Sir
+
+ Ham. What woman then?
+ Clo. For none neither
+
+ Ham. Who is to be buried in't?
+ Clo. One that was a woman Sir; but rest her Soule,
+shee's dead
+
+ Ham. How absolute the knaue is? wee must speake
+by the Carde, or equiuocation will vndoe vs: by the
+Lord Horatio, these three yeares I haue taken note of it,
+the Age is growne so picked, that the toe of the Pesant
+comes so neere the heeles of our Courtier, hee galls his
+Kibe. How long hast thou been a Graue-maker?
+ Clo. Of all the dayes i'th' yeare, I came too't that day
+that our last King Hamlet o'recame Fortinbras
+
+ Ham. How long is that since?
+ Clo. Cannot you tell that? euery foole can tell that:
+It was the very day, that young Hamlet was borne, hee
+that was mad, and sent into England
+
+ Ham. I marry, why was he sent into England?
+ Clo. Why, because he was mad; hee shall recouer his
+wits there; or if he do not, it's no great matter there
+
+ Ham. Why?
+ Clo. 'Twill not be seene in him, there the men are as
+mad as he
+
+ Ham. How came he mad?
+ Clo. Very strangely they say
+
+ Ham. How strangely?
+ Clo. Faith e'ene with loosing his wits
+
+ Ham. Vpon what ground?
+ Clo. Why heere in Denmarke: I haue bin sixeteene
+heere, man and Boy thirty yeares
+
+ Ham. How long will a man lie i'th' earth ere he rot?
+ Clo. Ifaith, if he be not rotten before he die (as we haue
+many pocky Coarses now adaies, that will scarce hold
+the laying in) he will last you some eight yeare, or nine
+yeare. A Tanner will last you nine yeare
+
+ Ham. Why he, more then another?
+ Clo. Why sir, his hide is so tan'd with his Trade, that
+he will keepe out water a great while. And your water,
+is a sore Decayer of your horson dead body. Heres a Scull
+now: this Scul, has laine in the earth three & twenty years
+
+ Ham. Whose was it?
+ Clo. A whoreson mad Fellowes it was;
+Whose doe you thinke it was?
+ Ham. Nay, I know not
+
+ Clo. A pestilence on him for a mad Rogue, a pour'd a
+Flaggon of Renish on my head once. This same Scull
+Sir, this same Scull sir, was Yoricks Scull, the Kings Iester
+
+ Ham. This?
+ Clo. E'ene that
+
+ Ham. Let me see. Alas poore Yorick, I knew him Horatio,
+a fellow of infinite Iest; of most excellent fancy, he
+hath borne me on his backe a thousand times: And how
+abhorred my Imagination is, my gorge rises at it. Heere
+hung those lipps, that I haue kist I know not how oft.
+Where be your Iibes now? Your Gambals? Your
+Songs? Your flashes of Merriment that were wont to
+set the Table on a Rore? No one now to mock your own
+Ieering? Quite chopfalne? Now get you to my Ladies
+Chamber, and tell her, let her paint an inch thicke, to this
+fauour she must come. Make her laugh at that: prythee
+Horatio tell me one thing
+
+ Hor. What's that my Lord?
+ Ham. Dost thou thinke Alexander lookt o'this fashion
+i'th' earth?
+ Hor. E'ene so
+
+ Ham. And smelt so? Puh
+
+ Hor. E'ene so, my Lord
+
+ Ham. To what base vses we may returne Horatio.
+Why may not Imagination trace the Noble dust of Alexander,
+till he find it stopping a bunghole
+
+ Hor. 'Twere to consider: to curiously to consider so
+
+ Ham. No faith, not a iot. But to follow him thether
+with modestie enough, & likeliehood to lead it; as thus.
+Alexander died: Alexander was buried: Alexander returneth
+into dust; the dust is earth; of earth we make
+Lome, and why of that Lome (whereto he was conuerted)
+might they not stopp a Beere-barrell?
+Imperiall Caesar, dead and turn'd to clay,
+Might stop a hole to keepe the winde away.
+Oh, that that earth, which kept the world in awe,
+Should patch a Wall, t' expell the winters flaw.
+But soft, but soft, aside; heere comes the King.
+Enter King, Queene, Laertes, and a Coffin, with Lords attendant.
+
+The Queene, the Courtiers. Who is that they follow,
+And with such maimed rites? This doth betoken,
+The Coarse they follow, did with disperate hand,
+Fore do it owne life; 'twas some Estate.
+Couch we a while, and mark
+
+ Laer. What Cerimony else?
+ Ham. That is Laertes, a very Noble youth: Marke
+
+ Laer. What Cerimony else?
+ Priest. Her Obsequies haue bin as farre inlarg'd.
+As we haue warrantie, her death was doubtfull,
+And but that great Command, o're-swaies the order,
+She should in ground vnsanctified haue lodg'd,
+Till the last Trumpet. For charitable praier,
+Shardes, Flints, and Peebles, should be throwne on her:
+Yet heere she is allowed her Virgin Rites,
+Her Maiden strewments, and the bringing home
+Of Bell and Buriall
+
+ Laer. Must there no more be done ?
+ Priest. No more be done:
+We should prophane the seruice of the dead,
+To sing sage Requiem, and such rest to her
+As to peace-parted Soules
+
+ Laer. Lay her i'th' earth,
+And from her faire and vnpolluted flesh,
+May Violets spring. I tell thee (churlish Priest)
+A Ministring Angell shall my Sister be,
+When thou liest howling?
+ Ham. What, the faire Ophelia?
+ Queene. Sweets, to the sweet farewell.
+I hop'd thou should'st haue bin my Hamlets wife:
+I thought thy Bride-bed to haue deckt (sweet Maid)
+And not t'haue strew'd thy Graue
+
+ Laer. Oh terrible woer,
+Fall ten times trebble, on that cursed head
+Whose wicked deed, thy most Ingenious sence
+Depriu'd thee of. Hold off the earth a while,
+Till I haue caught her once more in mine armes:
+
+Leaps in the graue.
+
+Now pile your dust, vpon the quicke, and dead,
+Till of this flat a Mountaine you haue made,
+To o're top old Pelion, or the skyish head
+Of blew Olympus
+
+ Ham. What is he, whose griefes
+Beares such an Emphasis? whose phrase of Sorrow
+Coniure the wandring Starres, and makes them stand
+Like wonder-wounded hearers? This is I,
+Hamlet the Dane
+
+ Laer. The deuill take thy soule
+
+ Ham. Thou prai'st not well,
+I prythee take thy fingers from my throat;
+Sir though I am not Spleenatiue, and rash,
+Yet haue I something in me dangerous,
+Which let thy wisenesse feare. Away thy hand
+
+ King. Pluck them asunder
+
+ Qu. Hamlet, Hamlet
+
+ Gen. Good my Lord be quiet
+
+ Ham. Why I will fight with him vppon this Theme.
+Vntill my eielids will no longer wag
+
+ Qu. Oh my Sonne, what Theame?
+ Ham. I lou'd Ophelia; fortie thousand Brothers
+Could not (with all there quantitie of Loue)
+Make vp my summe. What wilt thou do for her?
+ King. Oh he is mad Laertes,
+ Qu. For loue of God forbeare him
+
+ Ham. Come show me what thou'lt doe.
+Woo't weepe? Woo't fight? Woo't teare thy selfe?
+Woo't drinke vp Esile, eate a Crocodile?
+Ile doo't. Dost thou come heere to whine;
+To outface me with leaping in her Graue?
+Be buried quicke with her, and so will I.
+And if thou prate of Mountaines; let them throw
+Millions of Akers on vs; till our ground
+Sindging his pate against the burning Zone,
+Make Ossa like a wart. Nay, and thou'lt mouth,
+Ile rant as well as thou
+
+ Kin. This is meere Madnesse:
+And thus awhile the fit will worke on him:
+Anon as patient as the female Doue,
+When that her Golden Cuplet are disclos'd;
+His silence will sit drooping
+
+ Ham. Heare you Sir:
+What is the reason that you vse me thus?
+I lou'd you euer; but it is no matter:
+Let Hercules himselfe doe what he may,
+The Cat will Mew, and Dogge will haue his day.
+Enter.
+
+ Kin. I pray you good Horatio wait vpon him,
+Strengthen your patience in our last nights speech,
+Wee'l put the matter to the present push:
+Good Gertrude set some watch ouer your Sonne,
+This Graue shall haue a liuing Monument:
+An houre of quiet shortly shall we see;
+Till then, in patience our proceeding be.
+
+Exeunt.
+
+Enter Hamlet and Horatio
+
+ Ham. So much for this Sir; now let me see the other,
+You doe remember all the Circumstance
+
+ Hor. Remember it my Lord?
+ Ham. Sir, in my heart there was a kinde of fighting,
+That would not let me sleepe; me thought I lay
+Worse then the mutines in the Bilboes, rashly,
+(And praise be rashnesse for it) let vs know,
+Our indiscretion sometimes serues vs well,
+When our deare plots do paule, and that should teach vs,
+There's a Diuinity that shapes our ends,
+Rough-hew them how we will
+
+ Hor. That is most certaine
+
+ Ham. Vp from my Cabin
+My sea-gowne scarft about me in the darke,
+Grop'd I to finde out them; had my desire,
+Finger'd their Packet, and in fine, withdrew
+To mine owne roome againe, making so bold,
+(My feares forgetting manners) to vnseale
+Their grand Commission, where I found Horatio,
+Oh royall knauery: An exact command,
+Larded with many seuerall sorts of reason;
+Importing Denmarks health, and Englands too,
+With hoo, such Bugges and Goblins in my life,
+That on the superuize no leasure bated,
+No not to stay the grinding of the Axe,
+My head should be struck off
+
+ Hor. Ist possible?
+ Ham. Here's the Commission, read it at more leysure:
+But wilt thou heare me how I did proceed?
+ Hor. I beseech you
+
+ Ham. Being thus benetted round with Villaines,
+Ere I could make a Prologue to my braines,
+They had begun the Play. I sate me downe,
+Deuis'd a new Commission, wrote it faire,
+I once did hold it as our Statists doe,
+A basenesse to write faire; and laboured much
+How to forget that learning: but Sir now,
+It did me Yeomans seriuce: wilt thou know
+The effects of what I wrote?
+ Hor. I, good my Lord
+
+ Ham. An earnest Coniuration from the King,
+As England was his faithfull Tributary,
+As loue betweene them, as the Palme should flourish,
+As Peace should still her wheaten Garland weare,
+And stand a Comma 'tweene their amities,
+And many such like Assis of great charge,
+That on the view and know of these Contents,
+Without debatement further, more or lesse,
+He should the bearers put to sodaine death,
+Not shriuing time allowed
+
+ Hor. How was this seal'd?
+ Ham. Why, euen in that was Heauen ordinate;
+I had my fathers Signet in my Purse,
+Which was the Modell of that Danish Seale:
+Folded the Writ vp in forme of the other,
+Subscrib'd it, gau't th' impression, plac't it safely,
+The changeling neuer knowne: Now, the next day
+Was our Sea Fight, and what to this was sement,
+Thou know'st already
+
+ Hor. So Guildensterne and Rosincrance, go too't
+
+ Ham. Why man, they did make loue to this imployment
+They are not neere my Conscience; their debate
+Doth by their owne insinuation grow:
+'Tis dangerous, when the baser nature comes
+Betweene the passe, and fell incensed points
+Of mighty opposites
+
+ Hor. Why, what a King is this?
+ Ham. Does it not, thinkst thee, stand me now vpon
+He that hath kil'd my King, and whor'd my Mother,
+Popt in betweene th' election and my hopes,
+Throwne out his Angle for my proper life,
+And with such coozenage; is't not perfect conscience,
+To quit him with this arme? And is't not to be damn'd
+To let this Canker of our nature come
+In further euill
+
+ Hor. It must be shortly knowne to him from England
+What is the issue of the businesse there
+
+ Ham. It will be short,
+The interim's mine, and a mans life's no more
+Then to say one: but I am very sorry good Horatio,
+That to Laertes I forgot my selfe;
+For by the image of my Cause, I see
+The Portraiture of his; Ile count his fauours:
+But sure the brauery of his griefe did put me
+Into a Towring passion
+
+ Hor. Peace, who comes heere?
+Enter young Osricke.
+
+ Osr. Your Lordship is right welcome back to Denmarke
+
+ Ham. I humbly thank you Sir, dost know this waterflie?
+ Hor. No my good Lord
+
+ Ham. Thy state is the more gracious; for 'tis a vice to
+know him: he hath much Land, and fertile; let a Beast
+be Lord of Beasts, and his Crib shall stand at the Kings
+Messe; 'tis a Chowgh; but as I saw spacious in the possession
+of dirt
+
+ Osr. Sweet Lord, if your friendship were at leysure,
+I should impart a thing to you from his Maiesty
+
+ Ham. I will receiue it with all diligence of spirit; put
+your Bonet to his right vse, 'tis for the head
+
+ Osr. I thanke your Lordship, 'tis very hot
+
+ Ham. No, beleeue mee 'tis very cold, the winde is
+Northerly
+
+ Osr. It is indifferent cold my Lord indeed
+
+ Ham. Mee thinkes it is very soultry, and hot for my
+Complexion
+
+ Osr. Exceedingly, my Lord, it is very soultry, as 'twere
+I cannot tell how: but my Lord, his Maiesty bad me signifie
+to you, that he ha's laid a great wager on your head:
+Sir, this is the matter
+
+ Ham. I beseech you remember
+
+ Osr. Nay, in good faith, for mine ease in good faith:
+Sir, you are not ignorant of what excellence Laertes is at
+his weapon
+
+ Ham. What's his weapon?
+ Osr. Rapier and dagger
+
+ Ham. That's two of his weapons; but well
+
+ Osr. The sir King ha's wag'd with him six Barbary horses,
+against the which he impon'd as I take it, sixe French
+Rapiers and Poniards, with their assignes, as Girdle,
+Hangers or so: three of the Carriages infaith are very
+deare to fancy, very responsiue to the hilts, most delicate
+carriages, and of very liberall conceit
+
+ Ham. What call you the Carriages?
+ Osr. The Carriages Sir, are the hangers
+
+ Ham. The phrase would bee more Germaine to the
+matter: If we could carry Cannon by our sides; I would
+it might be Hangers till then; but on sixe Barbary Horses
+against sixe French Swords: their Assignes, and three
+liberall conceited Carriages, that's the French but against
+the Danish; why is this impon'd as you call it?
+ Osr. The King Sir, hath laid that in a dozen passes betweene
+you and him, hee shall not exceed you three hits;
+He hath one twelue for mine, and that would come to
+imediate tryall, if your Lordship would vouchsafe the
+Answere
+
+ Ham. How if I answere no?
+ Osr. I meane my Lord, the opposition of your person
+in tryall
+
+ Ham. Sir, I will walke heere in the Hall; if it please
+his Maiestie, 'tis the breathing time of day with me; let
+the Foyles bee brought, the Gentleman willing, and the
+King hold his purpose; I will win for him if I can: if
+not, Ile gaine nothing but my shame, and the odde hits
+
+ Osr. Shall I redeliuer you ee'n so?
+ Ham. To this effect Sir, after what flourish your nature
+will
+
+ Osr. I commend my duty to your Lordship
+
+ Ham. Yours, yours; hee does well to commend it
+himselfe, there are no tongues else for's tongue
+
+ Hor. This Lapwing runs away with the shell on his
+head
+
+ Ham. He did Complie with his Dugge before hee
+suck't it: thus had he and mine more of the same Beauty
+that I know the drossie age dotes on; only got the tune of
+the time, and outward habite of encounter, a kinde of
+yesty collection, which carries them through & through
+the most fond and winnowed opinions; and doe but blow
+them to their tryalls: the Bubbles are out
+
+ Hor. You will lose this wager, my Lord
+
+ Ham. I doe not thinke so, since he went into France,
+I haue beene in continuall practice; I shall winne at the
+oddes: but thou wouldest not thinke how all heere about
+my heart: but it is no matter
+
+ Hor. Nay, good my Lord
+
+ Ham. It is but foolery; but it is such a kinde of
+gain-giuing as would perhaps trouble a woman
+
+ Hor. If your minde dislike any thing, obey. I will forestall
+their repaire hither, and say you are not fit
+
+ Ham. Not a whit, we defie Augury; there's a speciall
+Prouidence in the fall of a sparrow. If it be now, 'tis not
+to come: if it bee not to come, it will bee now: if it
+be not now; yet it will come; the readinesse is all, since no
+man ha's ought of what he leaues. What is't to leaue betimes?
+Enter King, Queene, Laertes and Lords, with other Attendants with
+Foyles,
+and Gauntlets, a Table and Flagons of Wine on it.
+
+ Kin. Come Hamlet, come, and take this hand from me
+
+ Ham. Giue me your pardon Sir, I'ue done you wrong,
+But pardon't as you are a Gentleman.
+This presence knowes,
+And you must needs haue heard how I am punisht
+With sore distraction? What I haue done
+That might your nature honour, and exception
+Roughly awake, I heere proclaime was madnesse:
+Was't Hamlet wrong'd Laertes? Neuer Hamlet.
+If Hamlet from himselfe be tane away:
+And when he's not himselfe, do's wrong Laertes,
+Then Hamlet does it not, Hamlet denies it:
+Who does it then? His Madnesse? If't be so,
+Hamlet is of the Faction that is wrong'd,
+His madnesse is poore Hamlets Enemy.
+Sir, in this Audience,
+Let my disclaiming from a purpos'd euill,
+Free me so farre in your most generous thoughts,
+That I haue shot mine Arrow o're the house,
+And hurt my Mother
+
+ Laer. I am satisfied in Nature,
+Whose motiue in this case should stirre me most
+To my Reuenge. But in my termes of Honor
+I stand aloofe, and will no reconcilement,
+Till by some elder Masters of knowne Honor,
+I haue a voyce, and president of peace
+To keepe my name vngorg'd. But till that time,
+I do receiue your offer'd loue like loue,
+And wil not wrong it
+
+ Ham. I do embrace it freely,
+And will this Brothers wager frankely play.
+Giue vs the Foyles: Come on
+
+ Laer. Come one for me
+
+ Ham. Ile be your foile Laertes, in mine ignorance,
+Your Skill shall like a Starre i'th' darkest night,
+Sticke fiery off indeede
+
+ Laer. You mocke me Sir
+
+ Ham. No by this hand
+
+ King. Giue them the Foyles yong Osricke,
+Cousen Hamlet, you know the wager
+
+ Ham. Verie well my Lord,
+Your Grace hath laide the oddes a'th' weaker side
+
+ King. I do not feare it,
+I haue seene you both:
+But since he is better'd, we haue therefore oddes
+
+ Laer. This is too heauy,
+Let me see another
+
+ Ham. This likes me well,
+These Foyles haue all a length.
+
+Prepare to play.
+
+ Osricke. I my good Lord
+
+ King. Set me the Stopes of wine vpon that Table:
+If Hamlet giue the first, or second hit,
+Or quit in answer of the third exchange,
+Let all the Battlements their Ordinance fire,
+The King shal drinke to Hamlets better breath,
+And in the Cup an vnion shal he throw
+Richer then that, which foure successiue Kings
+In Denmarkes Crowne haue worne.
+Giue me the Cups,
+And let the Kettle to the Trumpets speake,
+The Trumpet to the Cannoneer without,
+The Cannons to the Heauens, the Heauen to Earth,
+Now the King drinkes to Hamlet. Come, begin,
+And you the Iudges beare a wary eye
+
+ Ham. Come on sir
+
+ Laer. Come on sir.
+
+They play.
+
+ Ham. One
+
+ Laer. No
+
+ Ham. Iudgement
+
+ Osr. A hit, a very palpable hit
+
+ Laer. Well: againe
+
+ King. Stay, giue me drinke.
+Hamlet, this Pearle is thine,
+Here's to thy health. Giue him the cup,
+
+Trumpets sound, and shot goes off.
+
+ Ham. Ile play this bout first, set by a-while.
+Come: Another hit; what say you?
+ Laer. A touch, a touch, I do confesse
+
+ King. Our Sonne shall win
+
+ Qu. He's fat, and scant of breath.
+Heere's a Napkin, rub thy browes,
+The Queene Carowses to thy fortune, Hamlet
+
+ Ham. Good Madam
+
+ King. Gertrude, do not drinke
+
+ Qu. I will my Lord;
+I pray you pardon me
+
+ King. It is the poyson'd Cup, it is too late
+
+ Ham. I dare not drinke yet Madam,
+By and by
+
+ Qu. Come, let me wipe thy face
+
+ Laer. My Lord, Ile hit him now
+
+ King. I do not thinke't
+
+ Laer. And yet 'tis almost 'gainst my conscience
+
+ Ham. Come for the third.
+Laertes, you but dally,
+I pray you passe with your best violence,
+I am affear'd you make a wanton of me
+
+ Laer. Say you so? Come on.
+
+Play.
+
+ Osr. Nothing neither way
+
+ Laer. Haue at you now.
+
+In scuffling they change Rapiers.
+
+ King. Part them, they are incens'd
+
+ Ham. Nay come, againe
+
+ Osr. Looke to the Queene there hoa
+
+ Hor. They bleed on both sides. How is't my Lord?
+ Osr. How is't Laertes?
+ Laer. Why as a Woodcocke
+To mine Sprindge, Osricke,
+I am iustly kill'd with mine owne Treacherie
+
+ Ham. How does the Queene?
+ King. She sounds to see them bleede
+
+ Qu. No, no, the drinke, the drinke.
+Oh my deere Hamlet, the drinke, the drinke,
+I am poyson'd
+
+ Ham. Oh Villany! How? Let the doore be lock'd.
+Treacherie, seeke it out
+
+ Laer. It is heere Hamlet.
+Hamlet, thou art slaine,
+No Medicine in the world can do thee good.
+In thee, there is not halfe an houre of life;
+The Treacherous Instrument is in thy hand,
+Vnbated and envenom'd: the foule practise
+Hath turn'd it selfe on me. Loe, heere I lye,
+Neuer to rise againe: Thy Mothers poyson'd:
+I can no more, the King, the King's too blame
+
+ Ham. The point envenom'd too,
+Then venome to thy worke.
+
+Hurts the King.
+
+ All. Treason, Treason
+
+ King. O yet defend me Friends, I am but hurt
+
+ Ham. Heere thou incestuous, murdrous,
+Damned Dane,
+Drinke off this Potion: Is thy Vnion heere?
+Follow my Mother.
+
+King Dyes.
+
+ Laer. He is iustly seru'd.
+It is a poyson temp'red by himselfe:
+Exchange forgiuenesse with me, Noble Hamlet;
+Mine and my Fathers death come not vpon thee,
+Nor thine on me.
+
+Dyes.
+
+ Ham. Heauen make thee free of it, I follow thee.
+I am dead Horatio, wretched Queene adiew,
+You that looke pale, and tremble at this chance,
+That are but Mutes or audience to this acte:
+Had I but time (as this fell Sergeant death
+Is strick'd in his Arrest) oh I could tell you.
+But let it be: Horatio, I am dead,
+Thou liu'st, report me and my causes right
+To the vnsatisfied
+
+ Hor. Neuer beleeue it.
+I am more an Antike Roman then a Dane:
+Heere's yet some Liquor left
+
+ Ham. As th'art a man, giue me the Cup.
+Let go, by Heauen Ile haue't.
+Oh good Horatio, what a wounded name,
+(Things standing thus vnknowne) shall liue behind me.
+If thou did'st euer hold me in thy heart,
+Absent thee from felicitie awhile,
+And in this harsh world draw thy breath in paine,
+To tell my Storie.
+
+March afarre off, and shout within.
+
+What warlike noyse is this?
+Enter Osricke.
+
+ Osr. Yong Fortinbras, with conquest come fro[m] Poland
+To th' Ambassadors of England giues this warlike volly
+
+ Ham. O I dye Horatio:
+The potent poyson quite ore-crowes my spirit,
+I cannot liue to heare the Newes from England,
+But I do prophesie th' election lights
+On Fortinbras, he ha's my dying voyce,
+So tell him with the occurrents more and lesse,
+Which haue solicited. The rest is silence. O, o, o, o.
+
+Dyes
+
+ Hora. Now cracke a Noble heart:
+Goodnight sweet Prince,
+And flights of Angels sing thee to thy rest,
+Why do's the Drumme come hither?
+Enter Fortinbras and English Ambassador, with Drumme, Colours,
+and
+Attendants.
+
+ Fortin. Where is this sight?
+ Hor. What is it ye would see;
+If ought of woe, or wonder, cease your search
+
+ For. His quarry cries on hauocke. Oh proud death,
+What feast is toward in thine eternall Cell.
+That thou so many Princes, at a shoote,
+So bloodily hast strooke
+
+ Amb. The sight is dismall,
+And our affaires from England come too late,
+The eares are senselesse that should giue vs hearing,
+To tell him his command'ment is fulfill'd,
+That Rosincrance and Guildensterne are dead:
+Where should we haue our thankes?
+ Hor. Not from his mouth,
+Had it th' abilitie of life to thanke you:
+He neuer gaue command'ment for their death.
+But since so iumpe vpon this bloodie question,
+You from the Polake warres, and you from England
+Are heere arriued. Giue order that these bodies
+High on a stage be placed to the view,
+And let me speake to th' yet vnknowing world,
+How these things came about. So shall you heare
+Of carnall, bloudie, and vnnaturall acts,
+Of accidentall iudgements, casuall slaughters
+Of death's put on by cunning, and forc'd cause,
+And in this vpshot, purposes mistooke,
+Falne on the Inuentors head. All this can I
+Truly deliuer
+
+ For. Let vs hast to heare it,
+And call the Noblest to the Audience.
+For me, with sorrow, I embrace my Fortune,
+I haue some Rites of memory in this Kingdome,
+Which are to claime, my vantage doth
+Inuite me,
+ Hor. Of that I shall haue alwayes cause to speake,
+And from his mouth
+Whose voyce will draw on more:
+But let this same be presently perform'd,
+Euen whiles mens mindes are wilde,
+Lest more mischance
+On plots, and errors happen
+
+ For. Let foure Captaines
+Beare Hamlet like a Soldier to the Stage,
+For he was likely, had he beene put on
+To haue prou'd most royally:
+And for his passage,
+The Souldiours Musicke, and the rites of Warre
+Speake lowdly for him.
+Take vp the body; Such a sight as this
+Becomes the Field, but heere shewes much amis.
+Go, bid the Souldiers shoote.
+
+Exeunt. Marching: after the which, a Peale of Ordenance are shot
+off.
+
+
+FINIS. The tragedie of HAMLET, Prince of Denmarke.
diff --git a/java-strings-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java b/java-strings-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java
new file mode 100644
index 0000000000..50d9a2b058
--- /dev/null
+++ b/java-strings-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java
@@ -0,0 +1,58 @@
+package com.baeldung.initialization;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+
+import org.junit.Test;
+
+public class StringInitializationUnitTest {
+
+ private String fieldString;
+
+ void printDeclaredOnlyString() {
+ String localVarString = null;
+
+ System.out.println(localVarString); // compilation error
+ System.out.println(fieldString);
+ }
+
+ @Test
+ public void givenDeclaredFeldStringAndNullString_thenCompareEquals() {
+ String localVarString = null;
+
+ assertEquals(fieldString, localVarString);
+ }
+
+ @Test
+ public void givenTwoStringsWithSameLiteral_thenCompareReferencesEquals() {
+ String literalOne = "Baeldung";
+ String literalTwo = "Baeldung";
+
+ assertTrue(literalOne == literalTwo);
+ }
+
+ @Test
+ public void givenTwoStringsUsingNew_thenCompareReferencesNotEquals() {
+ String newStringOne = new String("Baeldung");
+ String newStringTwo = new String("Baeldung");
+
+ assertFalse(newStringOne == newStringTwo);
+ }
+
+ @Test
+ public void givenEmptyLiteralStringsAndNewObject_thenCompareEquals() {
+ String emptyLiteral = "";
+ String emptyNewString = new String("");
+
+ assertEquals(emptyLiteral, emptyNewString);
+ }
+
+ @Test
+ public void givenEmptyStringObjects_thenCompareEquals() {
+ String emptyNewString = new String("");
+ String emptyNewStringTwo = new String();
+
+ assertEquals(emptyNewString, emptyNewStringTwo);
+ }
+}
diff --git a/java-strings-2/src/test/java/com/baeldung/string/RemoveStopwordsUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/RemoveStopwordsUnitTest.java
new file mode 100644
index 0000000000..edda2ec9d7
--- /dev/null
+++ b/java-strings-2/src/test/java/com/baeldung/string/RemoveStopwordsUnitTest.java
@@ -0,0 +1,60 @@
+package com.baeldung.string;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class RemoveStopwordsUnitTest {
+ final String original = "The quick brown fox jumps over the lazy dog";
+ final String target = "quick brown fox jumps lazy dog";
+ static List stopwords;
+
+ @BeforeClass
+ public static void loadStopwords() throws IOException {
+ stopwords = Files.readAllLines(Paths.get("src/main/resources/english_stopwords.txt"));
+ }
+
+ @Test
+ public void whenRemoveStopwordsManually_thenSuccess() {
+ String[] allWords = original.toLowerCase()
+ .split(" ");
+ StringBuilder builder = new StringBuilder();
+ for (String word : allWords) {
+ if (!stopwords.contains(word)) {
+ builder.append(word);
+ builder.append(' ');
+ }
+ }
+
+ String result = builder.toString().trim();
+ assertEquals(result, target);
+ }
+
+ @Test
+ public void whenRemoveStopwordsUsingRemoveAll_thenSuccess() {
+ ArrayList allWords = Stream.of(original.toLowerCase()
+ .split(" "))
+ .collect(Collectors.toCollection(ArrayList::new));
+ allWords.removeAll(stopwords);
+ String result = allWords.stream().collect(Collectors.joining(" "));
+ assertEquals(result, target);
+ }
+
+ @Test
+ public void whenRemoveStopwordsUsingRegex_thenSuccess() {
+ String stopwordsRegex = stopwords.stream()
+ .collect(Collectors.joining("|", "\\b(", ")\\b\\s?"));
+ String result = original.toLowerCase().replaceAll(stopwordsRegex, "");
+ assertEquals(result, target);
+ }
+
+}
diff --git a/jhipster-5/README.md b/jhipster-5/README.md
new file mode 100644
index 0000000000..0537f5b1a5
--- /dev/null
+++ b/jhipster-5/README.md
@@ -0,0 +1,3 @@
+## Relevant articles:
+
+- [Creating New APIs and Views in JHipster](https://www.baeldung.com/jhipster-new-apis-and-views)
diff --git a/kotlin-libraries-2/pom.xml b/kotlin-libraries-2/pom.xml
index e2e261cb1b..14ac61a093 100644
--- a/kotlin-libraries-2/pom.xml
+++ b/kotlin-libraries-2/pom.xml
@@ -18,14 +18,16 @@
com.fasterxml.jackson.module
jackson-module-kotlin
+
+ io.reactivex.rxjava2
+ rxkotlin
+ 2.3.0
+
junit
junit
test
-
-
-
diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/rxkotlin/RxKotlinTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/rxkotlin/RxKotlinTest.kt
new file mode 100644
index 0000000000..979ed3f809
--- /dev/null
+++ b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/rxkotlin/RxKotlinTest.kt
@@ -0,0 +1,157 @@
+package com.baeldung.kotlin.rxkotlin
+
+import io.reactivex.Maybe
+import io.reactivex.Observable
+import io.reactivex.functions.BiFunction
+import io.reactivex.rxkotlin.*
+import io.reactivex.subjects.PublishSubject
+import org.junit.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+
+class RxKotlinTest {
+
+ @Test
+ fun whenBooleanArrayToObserver_thenBooleanObserver() {
+ val observable = listOf(true, false, false).toObservable()
+ observable.test().assertValues(true, false, false)
+ }
+
+ @Test
+ fun whenBooleanArrayToFlowable_thenBooleanFlowable() {
+ val flowable = listOf(true, false, false).toFlowable()
+ flowable.buffer(2).test().assertValues(listOf(true, false), listOf(false))
+ }
+
+ @Test
+ fun whenIntArrayToObserver_thenIntObserver() {
+ val observable = listOf(1, 1, 2, 3).toObservable()
+ observable.test().assertValues(1, 1, 2, 3)
+ }
+
+ @Test
+ fun whenIntArrayToFlowable_thenIntFlowable() {
+ val flowable = listOf(1, 1, 2, 3).toFlowable()
+ flowable.buffer(2).test().assertValues(listOf(1, 1), listOf(2, 3))
+ }
+
+ @Test
+ fun whenObservablePairToMap_thenSingleNoDuplicates() {
+ val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4))
+ val observable = list.toObservable()
+ val map = observable.toMap()
+ assertEquals(mapOf(Pair("a", 4), Pair("b", 2), Pair("c", 3)), map.blockingGet())
+ }
+
+ @Test
+ fun whenObservablePairToMap_thenSingleWithDuplicates() {
+ val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4))
+ val observable = list.toObservable()
+ val map = observable.toMultimap()
+ assertEquals(
+ mapOf(Pair("a", listOf(1, 4)), Pair("b", listOf(2)), Pair("c", listOf(3))),
+ map.blockingGet())
+ }
+
+ @Test
+ fun whenMergeAll_thenStream() {
+ val subject = PublishSubject.create>()
+ val observable = subject.mergeAll()
+ val testObserver = observable.test()
+ subject.onNext(Observable.just("first", "second"))
+ testObserver.assertValues("first", "second")
+ subject.onNext(Observable.just("third", "fourth"))
+ subject.onNext(Observable.just("fifth"))
+ testObserver.assertValues("first", "second", "third", "fourth", "fifth")
+ }
+
+ @Test
+ fun whenConcatAll_thenStream() {
+ val subject = PublishSubject.create>()
+ val observable = subject.concatAll()
+ val testObserver = observable.test()
+ subject.onNext(Observable.just("first", "second"))
+ testObserver.assertValues("first", "second")
+ subject.onNext(Observable.just("third", "fourth"))
+ subject.onNext(Observable.just("fifth"))
+ testObserver.assertValues("first", "second", "third", "fourth", "fifth")
+ }
+
+ @Test
+ fun whenSwitchLatest_thenStream() {
+ val subject = PublishSubject.create>()
+ val observable = subject.switchLatest()
+ val testObserver = observable.test()
+ subject.onNext(Observable.just("first", "second"))
+ testObserver.assertValues("first", "second")
+ subject.onNext(Observable.just("third", "fourth"))
+ subject.onNext(Observable.just("fifth"))
+ testObserver.assertValues("first", "second", "third", "fourth", "fifth")
+ }
+
+ @Test
+ fun whenMergeAllMaybes_thenObservable() {
+ val subject = PublishSubject.create>()
+ val observable = subject.mergeAllMaybes()
+ val testObserver = observable.test()
+ subject.onNext(Maybe.just(1))
+ subject.onNext(Maybe.just(2))
+ subject.onNext(Maybe.empty())
+ testObserver.assertValues(1, 2)
+ subject.onNext(Maybe.error(Exception("")))
+ subject.onNext(Maybe.just(3))
+ testObserver.assertValues(1, 2).assertError(Exception::class.java)
+ }
+
+ @Test
+ fun whenMerge_thenStream() {
+ val observables = mutableListOf(Observable.just("first", "second"))
+ val observable = observables.merge()
+ observables.add(Observable.just("third", "fourth"))
+ observables.add(Observable.error(Exception("e")))
+ observables.add(Observable.just("fifth"))
+
+ observable.test().assertValues("first", "second", "third", "fourth").assertError(Exception::class.java)
+ }
+
+ @Test
+ fun whenMergeDelayError_thenStream() {
+ val observables = mutableListOf>(Observable.error(Exception("e1")))
+ val observable = observables.mergeDelayError()
+ observables.add(Observable.just("1", "2"))
+ observables.add(Observable.error(Exception("e2")))
+ observables.add(Observable.just("3"))
+
+ observable.test().assertValues("1", "2", "3").assertError(Exception::class.java)
+ }
+
+ @Test
+ fun whenCast_thenUniformType() {
+ val observable = Observable.just(1, 1, 2, 3)
+ observable.cast().test().assertValues(1, 1, 2, 3)
+ }
+
+ @Test
+ fun whenOfType_thenFilter() {
+ val observable = Observable.just(1, "and", 2, "and")
+ observable.ofType().test().assertValues(1, 2)
+ }
+
+ @Test
+ fun whenFunction_thenCompletable() {
+ var value = 0
+ val completable = { value = 3 }.toCompletable()
+ assertFalse(completable.test().isCancelled)
+ assertEquals(3, value)
+ }
+
+ @Test
+ fun whenHelper_thenMoreIdiomaticKotlin() {
+ val zipWith = Observable.just(1).zipWith(Observable.just(2)) { a, b -> a + b }
+ zipWith.subscribeBy(onNext = { println(it) })
+ val zip = Observables.zip(Observable.just(1), Observable.just(2)) { a, b -> a + b }
+ zip.subscribeBy(onNext = { println(it) })
+ val zipOrig = Observable.zip(Observable.just(1), Observable.just(2), BiFunction { a, b -> a + b })
+ zipOrig.subscribeBy(onNext = { println(it) })
+ }
+}
diff --git a/kotlin-libraries/build.gradle b/kotlin-libraries/build.gradle
index afb92de49e..db23a438a0 100644
--- a/kotlin-libraries/build.gradle
+++ b/kotlin-libraries/build.gradle
@@ -54,9 +54,8 @@ dependencies {
testCompile group: 'org.jetbrains.spek', name: 'spek-subject-extension', version: '1.1.5'
testCompile group: 'org.jetbrains.spek', name: 'spek-junit-platform-engine', version: '1.1.5'
implementation 'com.beust:klaxon:3.0.1'
- implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'
-
}
+
task runServer(type: JavaExec) {
main = 'APIServer'
classpath = sourceSets.main.runtimeClasspath
diff --git a/libraries-2/README.md b/libraries-2/README.md
index 3d5dba80ee..8243b9f82c 100644
--- a/libraries-2/README.md
+++ b/libraries-2/README.md
@@ -1,3 +1,7 @@
-## Relevant Articles
+### Relevant Articles:
+
+- [A Guide to jBPM with Java](https://www.baeldung.com/jbpm-java)
- [Guide to Classgraph Library](https://www.baeldung.com/classgraph)
+- [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program)
+
diff --git a/logging-modules/logback/README.md b/logging-modules/logback/README.md
index df55492b69..58dc8ce541 100644
--- a/logging-modules/logback/README.md
+++ b/logging-modules/logback/README.md
@@ -1,3 +1,4 @@
### Relevant Articles:
- [Get Log Output in JSON](https://www.baeldung.com/java-log-json-output)
+- [SLF4J Warning: Class Path Contains Multiple SLF4J Bindings](https://www.baeldung.com/slf4j-classpath-multiple-bindings)
diff --git a/persistence-modules/README.md b/persistence-modules/README.md
index 2fbaf25f2f..e9a7d625cc 100644
--- a/persistence-modules/README.md
+++ b/persistence-modules/README.md
@@ -5,7 +5,6 @@
### Relevant Articles:
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
-- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
- [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce)
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
@@ -13,3 +12,6 @@
- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive)
- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
+- [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate)
+- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)
+- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences)
diff --git a/persistence-modules/core-java-persistence/README.md b/persistence-modules/core-java-persistence/README.md
index 26bd4bf00f..1187cc15c4 100644
--- a/persistence-modules/core-java-persistence/README.md
+++ b/persistence-modules/core-java-persistence/README.md
@@ -8,3 +8,4 @@
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
- [A Simple Guide to Connection Pooling in Java](https://www.baeldung.com/java-connection-pooling)
- [Guide to the JDBC ResultSet Interface](https://www.baeldung.com/jdbc-resultset)
+- [Types of SQL Joins](https://www.baeldung.com/sql-joins)
diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md
new file mode 100644
index 0000000000..223d93e1ed
--- /dev/null
+++ b/persistence-modules/hibernate-mapping/README.md
@@ -0,0 +1,4 @@
+
+### Relevant Articles:
+
+- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)
diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md
index 5be1015942..34d03b3259 100644
--- a/persistence-modules/java-jpa/README.md
+++ b/persistence-modules/java-jpa/README.md
@@ -2,8 +2,9 @@
- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)
-- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”]](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
+- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph)
- [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time)
- [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date)
- [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates)
+- [Types of JPA Queries](https://www.baeldung.com/jpa-queries)
diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/basicannotation/Course.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/basicannotation/Course.java
new file mode 100644
index 0000000000..cc5a83420c
--- /dev/null
+++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/basicannotation/Course.java
@@ -0,0 +1,33 @@
+package com.baeldung.jpa.basicannotation;
+
+import javax.persistence.Basic;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Id;
+
+@Entity
+public class Course {
+
+ @Id
+ private int id;
+
+ @Basic(optional = false, fetch = FetchType.LAZY)
+ private String name;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
+
diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Student.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Student.java
new file mode 100644
index 0000000000..531bae40c5
--- /dev/null
+++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Student.java
@@ -0,0 +1,75 @@
+package com.baeldung.jpa.entity;
+
+import java.util.Date;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+import javax.persistence.Transient;
+
+import com.baeldung.util.Gender;
+
+@Entity
+@Table(name="STUDENT")
+public class Student {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+ @Column(name = "STUDENT_NAME", length = 50, nullable = false, unique = false)
+ private String name;
+ @Transient
+ private Integer age;
+ @Temporal(TemporalType.DATE)
+ private Date birthDate;
+ @Enumerated(EnumType.STRING)
+ private Gender gender;
+
+ 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 Integer getAge() {
+ return age;
+ }
+
+ public void setAge(Integer age) {
+ this.age = age;
+ }
+
+ public Date getBirthDate() {
+ return birthDate;
+ }
+
+ public void setBirthDate(Date birthDate) {
+ this.birthDate = birthDate;
+ }
+
+ public Gender getGender() {
+ return gender;
+ }
+
+ public void setGender(Gender gender) {
+ this.gender = gender;
+ }
+
+}
diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Article.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Article.java
new file mode 100644
index 0000000000..d534f44e14
--- /dev/null
+++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Article.java
@@ -0,0 +1,91 @@
+package com.baeldung.jpa.enums;
+
+import javax.persistence.*;
+
+@Entity
+public class Article {
+
+ @Id
+ private int id;
+
+ private String title;
+
+ @Enumerated(EnumType.ORDINAL)
+ private Status status;
+
+ @Enumerated(EnumType.STRING)
+ private Type type;
+
+ @Basic
+ private int priorityValue;
+
+ @Transient
+ private Priority priority;
+
+ private Category category;
+
+ public Article() {
+ }
+
+ @PostLoad
+ void fillTransient() {
+ if (priorityValue > 0) {
+ this.priority = Priority.of(priorityValue);
+ }
+ }
+
+ @PrePersist
+ void fillPersistent() {
+ if (priority != null) {
+ this.priorityValue = priority.getPriority();
+ }
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public Status getStatus() {
+ return status;
+ }
+
+ public void setStatus(Status status) {
+ this.status = status;
+ }
+
+ public Type getType() {
+ return type;
+ }
+
+ public void setType(Type type) {
+ this.type = type;
+ }
+
+ public Priority getPriority() {
+ return priority;
+ }
+
+ public void setPriority(Priority priority) {
+ this.priority = priority;
+ }
+
+ public Category getCategory() {
+ return category;
+ }
+
+ public void setCategory(Category category) {
+ this.category = category;
+ }
+}
diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Category.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Category.java
new file mode 100644
index 0000000000..83b81da01e
--- /dev/null
+++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Category.java
@@ -0,0 +1,17 @@
+package com.baeldung.jpa.enums;
+
+import java.util.stream.Stream;
+
+public enum Category {
+ SPORT("S"), MUSIC("M"), TECHNOLOGY("T");
+
+ private String code;
+
+ Category(String code) {
+ this.code = code;
+ }
+
+ public String getCode() {
+ return code;
+ }
+}
diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/CategoryConverter.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/CategoryConverter.java
new file mode 100644
index 0000000000..98960f1569
--- /dev/null
+++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/CategoryConverter.java
@@ -0,0 +1,28 @@
+package com.baeldung.jpa.enums;
+
+import javax.persistence.AttributeConverter;
+import javax.persistence.Converter;
+import java.util.stream.Stream;
+
+@Converter(autoApply = true)
+public class CategoryConverter implements AttributeConverter {
+ @Override
+ public String convertToDatabaseColumn(Category category) {
+ if (category == null) {
+ return null;
+ }
+ return category.getCode();
+ }
+
+ @Override
+ public Category convertToEntityAttribute(final String code) {
+ if (code == null) {
+ return null;
+ }
+
+ return Stream.of(Category.values())
+ .filter(c -> c.getCode().equals(code))
+ .findFirst()
+ .orElseThrow(IllegalArgumentException::new);
+ }
+}
diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Priority.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Priority.java
new file mode 100644
index 0000000000..42ee254303
--- /dev/null
+++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Priority.java
@@ -0,0 +1,24 @@
+package com.baeldung.jpa.enums;
+
+import java.util.stream.Stream;
+
+public enum Priority {
+ LOW(100), MEDIUM(200), HIGH(300);
+
+ private int priority;
+
+ private Priority(int priority) {
+ this.priority = priority;
+ }
+
+ public int getPriority() {
+ return priority;
+ }
+
+ public static Priority of(int priority) {
+ return Stream.of(Priority.values())
+ .filter(p -> p.getPriority() == priority)
+ .findFirst()
+ .orElseThrow(IllegalArgumentException::new);
+ }
+}
diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Status.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Status.java
new file mode 100644
index 0000000000..80d5662c7a
--- /dev/null
+++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Status.java
@@ -0,0 +1,5 @@
+package com.baeldung.jpa.enums;
+
+public enum Status {
+ OPEN, REVIEW, APPROVED, REJECTED;
+}
diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Type.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Type.java
new file mode 100644
index 0000000000..80459fbd3c
--- /dev/null
+++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Type.java
@@ -0,0 +1,5 @@
+package com.baeldung.jpa.enums;
+
+enum Type {
+ INTERNAL, EXTERNAL;
+}
diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/util/Gender.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/util/Gender.java
new file mode 100644
index 0000000000..13f08d995c
--- /dev/null
+++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/util/Gender.java
@@ -0,0 +1,6 @@
+package com.baeldung.util;
+
+public enum Gender {
+ MALE,
+ FEMALE
+}
diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml
index 21a757f490..9c5543bc3c 100644
--- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml
+++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml
@@ -26,6 +26,8 @@
org.hibernate.jpa.HibernatePersistenceProvider
com.baeldung.jpa.stringcast.Message
+ com.baeldung.jpa.enums.Article
+ com.baeldung.jpa.enums.CategoryConverter
true
@@ -145,5 +147,20 @@
-
-
+
+
+ org.hibernate.jpa.HibernatePersistenceProvider
+ com.baeldung.jpa.entity.Student
+ true
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java
new file mode 100644
index 0000000000..8580aa6602
--- /dev/null
+++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/basicannotation/BasicAnnotationIntegrationTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.jpa.basicannotation;
+
+import org.hibernate.PropertyValueException;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.AfterClass;
+import org.junit.Test;
+
+import java.io.IOException;
+
+public class BasicAnnotationIntegrationTest {
+
+ private static EntityManager entityManager;
+ private static EntityManagerFactory entityManagerFactory;
+
+ @BeforeClass
+ public void setup() {
+ entityManagerFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day");
+ entityManager = entityManagerFactory.createEntityManager();
+ }
+
+ @Test
+ public void givenACourse_whenCourseNamePresent_shouldPersist() {
+ Course course = new Course();
+ course.setName("Computers");
+
+ entityManager.persist(course);
+ entityManager.flush();
+ entityManager.clear();
+
+ }
+
+ @Test(expected = PropertyValueException.class)
+ public void givenACourse_whenCourseNameAbsent_shouldFail() {
+ Course course = new Course();
+
+ entityManager.persist(course);
+ entityManager.flush();
+ entityManager.clear();
+ }
+
+ @AfterClass
+ public void destroy() {
+
+ if (entityManager != null) {
+ entityManager.close();
+ }
+ if (entityManagerFactory != null) {
+ entityManagerFactory.close();
+ }
+ }
+}
diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/StudentEntityIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/StudentEntityIntegrationTest.java
new file mode 100644
index 0000000000..fdaaba5439
--- /dev/null
+++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/StudentEntityIntegrationTest.java
@@ -0,0 +1,91 @@
+package com.baeldung.jpa.entity;
+
+import static org.junit.Assert.assertEquals;
+
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.util.Date;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import javax.persistence.TypedQuery;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.baeldung.util.Gender;
+
+public class StudentEntityIntegrationTest {
+
+ private EntityManagerFactory emf;
+ private EntityManager em;
+
+ @Before
+ public void setup() {
+ emf = Persistence.createEntityManagerFactory("jpa-entity-definition");
+ em = emf.createEntityManager();
+ }
+
+ @Test
+ public void persistStudentThenRetrieveTheDetails() {
+ Student student = createStudentWithRelevantDetails();
+ persist(student);
+ clearThePersistenceContext();
+ List students = getStudentsFromTable();
+ checkAssertionsWith(students);
+ }
+
+ @After
+ public void destroy() {
+ if (em != null) {
+ em.close();
+ }
+ if (emf != null) {
+ emf.close();
+ }
+ }
+
+ private void clearThePersistenceContext() {
+ em.clear();
+ }
+
+ private void checkAssertionsWith(List students) {
+ assertEquals(1, students.size());
+ Student john = students.get(0);
+ assertEquals(1L, john.getId().longValue());
+ assertEquals(null, john.getAge());
+ assertEquals("John", john.getName());
+ }
+
+ private List getStudentsFromTable() {
+ String selectQuery = "SELECT student FROM Student student";
+ TypedQuery selectFromStudentTypedQuery = em.createQuery(selectQuery, Student.class);
+ List students = selectFromStudentTypedQuery.getResultList();
+ return students;
+ }
+
+ private void persist(Student student) {
+ em.getTransaction().begin();
+ em.persist(student);
+ em.getTransaction().commit();
+ }
+
+ private Student createStudentWithRelevantDetails() {
+ Student student = new Student();
+ student.setAge(20); // the 'age' field has been annotated with @Transient
+ student.setName("John");
+ Date date = getDate();
+ student.setBirthDate(date);
+ student.setGender(Gender.MALE);
+ return student;
+ }
+
+ private Date getDate() {
+ LocalDate localDate = LocalDate.of(2008, 7, 20);
+ return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
+ }
+
+}
diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/enums/ArticleUnitTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/enums/ArticleUnitTest.java
new file mode 100644
index 0000000000..82f3abc04d
--- /dev/null
+++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/enums/ArticleUnitTest.java
@@ -0,0 +1,118 @@
+package com.baeldung.jpa.enums;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.Persistence;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class ArticleUnitTest {
+
+ private static EntityManager em;
+ private static EntityManagerFactory emFactory;
+
+ @BeforeClass
+ public static void setup() {
+ Map properties = new HashMap();
+ properties.put("hibernate.show_sql", "true");
+ properties.put("hibernate.format_sql", "true");
+ emFactory = Persistence.createEntityManagerFactory("jpa-h2", properties);
+ em = emFactory.createEntityManager();
+ }
+
+ @Test
+ public void shouldPersistStatusEnumOrdinalValue() {
+ // given
+ Article article = new Article();
+ article.setId(1);
+ article.setTitle("ordinal title");
+ article.setStatus(Status.OPEN);
+
+ // when
+ EntityTransaction tx = em.getTransaction();
+ tx.begin();
+ em.persist(article);
+ tx.commit();
+
+ // then
+ Article persistedArticle = em.find(Article.class, 1);
+
+ assertEquals(1, persistedArticle.getId());
+ assertEquals("ordinal title", persistedArticle.getTitle());
+ assertEquals(Status.OPEN, persistedArticle.getStatus());
+ }
+
+ @Test
+ public void shouldPersistTypeEnumStringValue() {
+ // given
+ Article article = new Article();
+ article.setId(2);
+ article.setTitle("string title");
+ article.setType(Type.EXTERNAL);
+
+ // when
+ EntityTransaction tx = em.getTransaction();
+ tx.begin();
+ em.persist(article);
+ tx.commit();
+
+ // then
+ Article persistedArticle = em.find(Article.class, 2);
+
+ assertEquals(2, persistedArticle.getId());
+ assertEquals("string title", persistedArticle.getTitle());
+ assertEquals(Type.EXTERNAL, persistedArticle.getType());
+ }
+
+ @Test
+ public void shouldPersistPriorityIntValue() {
+ // given
+ Article article = new Article();
+ article.setId(3);
+ article.setTitle("callback title");
+ article.setPriority(Priority.HIGH);
+
+ // when
+ EntityTransaction tx = em.getTransaction();
+ tx.begin();
+ em.persist(article);
+ tx.commit();
+
+ // then
+ Article persistedArticle = em.find(Article.class, 3);
+
+ assertEquals(3, persistedArticle.getId());
+ assertEquals("callback title", persistedArticle.getTitle());
+ assertEquals(Priority.HIGH, persistedArticle.getPriority());
+
+ }
+
+ @Test
+ public void shouldPersistCategoryEnumConvertedValue() {
+ // given
+ Article article = new Article();
+ article.setId(4);
+ article.setTitle("converted title");
+ article.setCategory(Category.MUSIC);
+
+ // when
+ EntityTransaction tx = em.getTransaction();
+ tx.begin();
+ em.persist(article);
+ tx.commit();
+
+ // then
+ Article persistedArticle = em.find(Article.class, 4);
+
+ assertEquals(4, persistedArticle.getId());
+ assertEquals("converted title", persistedArticle.getTitle());
+ assertEquals(Category.MUSIC, persistedArticle.getCategory());
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md
index ded2b220f1..6d31467db3 100644
--- a/persistence-modules/java-mongodb/README.md
+++ b/persistence-modules/java-mongodb/README.md
@@ -2,3 +2,4 @@
- [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb)
- [A Simple Tagging Implementation with MongoDB](http://www.baeldung.com/mongodb-tagging)
+- [MongoDB BSON Guide](https://www.baeldung.com/mongodb-bson)
diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml
index 67a5c36fed..ba3baf6636 100644
--- a/persistence-modules/pom.xml
+++ b/persistence-modules/pom.xml
@@ -55,5 +55,6 @@
spring-hibernate-5
spring-hibernate4
spring-jpa
+ spring-persistence-simple
diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md
index 41381ab82a..393d15d6f1 100644
--- a/persistence-modules/spring-data-jpa-2/README.md
+++ b/persistence-modules/spring-data-jpa-2/README.md
@@ -1,6 +1,14 @@
-=========
-
-## Spring Data JPA Example Project
-
-### Relevant Articles:
-- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
+=========
+
+## Spring Data JPA Example Project
+
+### Relevant Articles:
+- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
+- [JPA Join Types](https://www.baeldung.com/jpa-join-types)
+- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries)
+- [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query)
+- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators)
+- [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters)
+- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections)
+- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable)
+- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete)
diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/derivedquery/entity/User.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/derivedquery/entity/User.java
new file mode 100644
index 0000000000..e6d38f775b
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/derivedquery/entity/User.java
@@ -0,0 +1,70 @@
+package com.baeldung.derivedquery.entity;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import java.time.ZonedDateTime;
+
+@Table(name = "users")
+@Entity
+public class User {
+
+ @Id
+ @GeneratedValue
+ private Integer id;
+ private String name;
+ private Integer age;
+ private ZonedDateTime birthDate;
+ private Boolean active;
+
+ public User() {
+ }
+
+ public User(String name, Integer age, ZonedDateTime birthDate, Boolean active) {
+ this.name = name;
+ this.age = age;
+ this.birthDate = birthDate;
+ this.active = active;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Integer getAge() {
+ return age;
+ }
+
+ public void setAge(Integer age) {
+ this.age = age;
+ }
+
+ public ZonedDateTime getBirthDate() {
+ return birthDate;
+ }
+
+ public void setBirthDate(ZonedDateTime birthDate) {
+ this.birthDate = birthDate;
+ }
+
+ public Boolean getActive() {
+ return active;
+ }
+
+ public void setActive(Boolean active) {
+ this.active = active;
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java
new file mode 100644
index 0000000000..a23855d96d
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java
@@ -0,0 +1,60 @@
+package com.baeldung.derivedquery.repository;
+
+import com.baeldung.derivedquery.entity.User;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+import java.time.ZonedDateTime;
+import java.util.Collection;
+import java.util.List;
+
+public interface UserRepository extends JpaRepository {
+
+ List findByName(String name);
+
+ List findByNameIs(String name);
+
+ List findByNameEquals(String name);
+
+ List findByNameIsNull();
+
+ List findByNameNot(String name);
+
+ List findByNameIsNot(String name);
+
+ List findByNameStartingWith(String name);
+
+ List findByNameEndingWith(String name);
+
+ List findByNameContaining(String name);
+
+ List findByNameLike(String name);
+
+ List findByAgeLessThan(Integer age);
+
+ List findByAgeLessThanEqual(Integer age);
+
+ List findByAgeGreaterThan(Integer age);
+
+ List findByAgeGreaterThanEqual(Integer age);
+
+ List findByAgeBetween(Integer startAge, Integer endAge);
+
+ List findByBirthDateAfter(ZonedDateTime birthDate);
+
+ List findByBirthDateBefore(ZonedDateTime birthDate);
+
+ List findByActiveTrue();
+
+ List findByActiveFalse();
+
+ List findByAgeIn(Collection ages);
+
+ List findByNameOrBirthDate(String name, ZonedDateTime birthDate);
+
+ List findByNameOrBirthDateAndActive(String name, ZonedDateTime birthDate, Boolean active);
+
+ List findByNameOrderByName(String name);
+
+ List findByNameOrderByNameDesc(String name);
+
+}
diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/like/model/Movie.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/like/model/Movie.java
new file mode 100644
index 0000000000..bba8bd35c4
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/like/model/Movie.java
@@ -0,0 +1,58 @@
+package com.baeldung.like.model;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Movie {
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ private Long id;
+ private String title;
+ private String director;
+ private String rating;
+ private int duration;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getDirector() {
+ return director;
+ }
+
+ public void setDirector(String director) {
+ this.director = director;
+ }
+
+ public String getRating() {
+ return rating;
+ }
+
+ public void setRating(String rating) {
+ this.rating = rating;
+ }
+
+ public int getDuration() {
+ return duration;
+ }
+
+ public void setDuration(int duration) {
+ this.duration = duration;
+ }
+
+}
diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/like/repository/MovieRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/like/repository/MovieRepository.java
new file mode 100644
index 0000000000..241bdd3306
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/like/repository/MovieRepository.java
@@ -0,0 +1,41 @@
+package com.baeldung.like.repository;
+
+import java.util.List;
+
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.CrudRepository;
+import org.springframework.data.repository.query.Param;
+
+import com.baeldung.like.model.Movie;
+
+public interface MovieRepository extends CrudRepository {
+
+ List findByTitleContaining(String title);
+
+ List findByTitleLike(String title);
+
+ List findByTitleContains(String title);
+
+ List findByTitleIsContaining(String title);
+
+ List findByRatingStartsWith(String rating);
+
+ List findByDirectorEndsWith(String director);
+
+ List findByTitleContainingIgnoreCase(String title);
+
+ List findByRatingNotContaining(String rating);
+
+ List findByDirectorNotLike(String director);
+
+ @Query("SELECT m FROM Movie m WHERE m.title LIKE %:title%")
+ List searchByTitleLike(@Param("title") String title);
+
+ @Query("SELECT m FROM Movie m WHERE m.rating LIKE ?1%")
+ List searchByRatingStartsWith(String rating);
+
+ //Escaping works in SpringBoot >= 2.4.1
+ //@Query("SELECT m FROM Movie m WHERE m.director LIKE %?#{escape([0])} escape ?#{escapeCharacter()}")
+ @Query("SELECT m FROM Movie m WHERE m.director LIKE %:#{[0]}")
+ List searchByDirectorEndsWith(String director);
+}
diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryTest.java
new file mode 100644
index 0000000000..188ed5d4d0
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryTest.java
@@ -0,0 +1,172 @@
+package com.baeldung.derivedquery.repository;
+
+import com.baeldung.Application;
+import com.baeldung.derivedquery.entity.User;
+import com.baeldung.derivedquery.repository.UserRepository;
+import java.time.ZonedDateTime;
+import java.util.Arrays;
+import java.util.List;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import static org.junit.Assert.assertEquals;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = Application.class)
+public class UserRepositoryTest {
+
+ private static final String USER_NAME_ADAM = "Adam";
+ private static final String USER_NAME_EVE = "Eve";
+ private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now();
+
+ @Autowired
+ private UserRepository userRepository;
+
+ @Before
+ public void setUp() {
+
+ User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true);
+ User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false);
+ User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true);
+ User user4 = new User(null, 30, BIRTHDATE, false);
+
+ userRepository.saveAll(Arrays.asList(user1, user2, user3, user4));
+ }
+
+ @After
+ public void tearDown() {
+
+ userRepository.deleteAll();
+ }
+
+ @Test
+ public void whenFindByName_thenReturnsCorrectResult() {
+
+ assertEquals(2, userRepository.findByName(USER_NAME_ADAM).size());
+ }
+
+ @Test
+ public void whenFindByNameIsNull_thenReturnsCorrectResult() {
+
+ assertEquals(1, userRepository.findByNameIsNull().size());
+ }
+
+ @Test
+ public void whenFindByNameNot_thenReturnsCorrectResult() {
+
+ assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM).get(0).getName());
+ }
+
+ @Test
+ public void whenFindByNameStartingWith_thenReturnsCorrectResult() {
+
+ assertEquals(2, userRepository.findByNameStartingWith("A").size());
+ }
+
+ @Test
+ public void whenFindByNameEndingWith_thenReturnsCorrectResult() {
+
+ assertEquals(1, userRepository.findByNameEndingWith("e").size());
+ }
+
+ @Test
+ public void whenByNameContaining_thenReturnsCorrectResult() {
+
+ assertEquals(1, userRepository.findByNameContaining("v").size());
+ }
+
+
+ @Test
+ public void whenByNameLike_thenReturnsCorrectResult() {
+
+ assertEquals(2, userRepository.findByNameEndingWith("%d%m").size());
+ }
+
+ @Test
+ public void whenByAgeLessThan_thenReturnsCorrectResult() {
+
+ assertEquals(2, userRepository.findByAgeLessThan(25).size());
+ }
+
+
+ @Test
+ public void whenByAgeLessThanEqual_thenReturnsCorrectResult() {
+
+ assertEquals(3, userRepository.findByAgeLessThanEqual(25).size());
+ }
+
+ @Test
+ public void whenByAgeGreaterThan_thenReturnsCorrectResult() {
+
+ assertEquals(1, userRepository.findByAgeGreaterThan(25).size());
+ }
+
+ @Test
+ public void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() {
+
+ assertEquals(2, userRepository.findByAgeGreaterThanEqual(25).size());
+ }
+
+ @Test
+ public void whenByAgeBetween_thenReturnsCorrectResult() {
+
+ assertEquals(4, userRepository.findByAgeBetween(20, 30).size());
+ }
+
+ @Test
+ public void whenByBirthDateAfter_thenReturnsCorrectResult() {
+
+ final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
+ assertEquals(4, userRepository.findByBirthDateAfter(yesterday).size());
+ }
+
+ @Test
+ public void whenByBirthDateBefore_thenReturnsCorrectResult() {
+
+ final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
+ assertEquals(0, userRepository.findByBirthDateBefore(yesterday).size());
+ }
+
+ @Test
+ public void whenByActiveTrue_thenReturnsCorrectResult() {
+
+ assertEquals(2, userRepository.findByActiveTrue().size());
+ }
+
+ @Test
+ public void whenByActiveFalse_thenReturnsCorrectResult() {
+
+ assertEquals(2, userRepository.findByActiveFalse().size());
+ }
+
+
+ @Test
+ public void whenByAgeIn_thenReturnsCorrectResult() {
+
+ final List ages = Arrays.asList(20, 25);
+ assertEquals(3, userRepository.findByAgeIn(ages).size());
+ }
+
+ @Test
+ public void whenByNameOrBirthDate() {
+
+ assertEquals(4, userRepository.findByNameOrBirthDate(USER_NAME_ADAM, BIRTHDATE).size());
+ }
+
+ @Test
+ public void whenByNameOrBirthDateAndActive() {
+
+ assertEquals(3, userRepository.findByNameOrBirthDateAndActive(USER_NAME_ADAM, BIRTHDATE, false).size());
+ }
+
+ @Test
+ public void whenByNameOrderByName() {
+
+ assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM).size());
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java
new file mode 100644
index 0000000000..99d7080792
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java
@@ -0,0 +1,88 @@
+package com.baeldung.like;
+
+import static org.junit.Assert.assertEquals;
+import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
+
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.jdbc.Sql;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import com.baeldung.like.model.Movie;
+import com.baeldung.like.repository.MovieRepository;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+@Sql(scripts = { "/test-movie-data.sql" })
+@Sql(scripts = "/test-movie-cleanup.sql", executionPhase = AFTER_TEST_METHOD)
+public class MovieRepositoryIntegrationTest {
+ @Autowired
+ private MovieRepository movieRepository;
+
+ @Test
+ public void givenPartialTitle_WhenFindByTitleContaining_ThenMoviesShouldReturn() {
+ List results = movieRepository.findByTitleContaining("in");
+ assertEquals(3, results.size());
+
+ results = movieRepository.findByTitleLike("%in%");
+ assertEquals(3, results.size());
+
+ results = movieRepository.findByTitleIsContaining("in");
+ assertEquals(3, results.size());
+
+ results = movieRepository.findByTitleContains("in");
+ assertEquals(3, results.size());
+ }
+
+ @Test
+ public void givenStartOfRating_WhenFindByRatingStartsWith_ThenMoviesShouldReturn() {
+ List results = movieRepository.findByRatingStartsWith("PG");
+ assertEquals(6, results.size());
+ }
+
+ @Test
+ public void givenLastName_WhenFindByDirectorEndsWith_ThenMoviesShouldReturn() {
+ List results = movieRepository.findByDirectorEndsWith("Burton");
+ assertEquals(1, results.size());
+ }
+
+ @Test
+ public void givenPartialTitle_WhenFindByTitleContainingIgnoreCase_ThenMoviesShouldReturn() {
+ List results = movieRepository.findByTitleContainingIgnoreCase("the");
+ assertEquals(2, results.size());
+ }
+
+ @Test
+ public void givenPartialTitle_WhenSearchByTitleLike_ThenMoviesShouldReturn() {
+ List results = movieRepository.searchByTitleLike("in");
+ assertEquals(3, results.size());
+ }
+
+ @Test
+ public void givenStartOfRating_SearchFindByRatingStartsWith_ThenMoviesShouldReturn() {
+ List results = movieRepository.searchByRatingStartsWith("PG");
+ assertEquals(6, results.size());
+ }
+
+ @Test
+ public void givenLastName_WhenSearchByDirectorEndsWith_ThenMoviesShouldReturn() {
+ List results = movieRepository.searchByDirectorEndsWith("Burton");
+ assertEquals(1, results.size());
+ }
+
+ @Test
+ public void givenPartialRating_findByRatingNotContaining_ThenMoviesShouldReturn() {
+ List results = movieRepository.findByRatingNotContaining("PG");
+ assertEquals(1, results.size());
+ }
+
+ @Test
+ public void givenPartialDirector_WhenFindByDirectorNotLike_ThenMoviesShouldReturn() {
+ List results = movieRepository.findByDirectorNotLike("An%");
+ assertEquals(5, results.size());
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-movie-cleanup.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-movie-cleanup.sql
new file mode 100644
index 0000000000..90aa15307c
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-2/src/test/resources/test-movie-cleanup.sql
@@ -0,0 +1 @@
+DELETE FROM Movie;
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-movie-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-movie-data.sql
new file mode 100644
index 0000000000..37f8e4fe64
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-2/src/test/resources/test-movie-data.sql
@@ -0,0 +1,7 @@
+INSERT INTO movie(id, title, director, rating, duration) VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132);
+INSERT INTO movie(id, title, director, rating, duration) VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181);
+INSERT INTO movie(id, title, director, rating, duration) VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123);
+INSERT INTO movie(id, title, director, rating, duration) VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112);
+INSERT INTO movie(id, title, director, rating, duration) VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102);
+INSERT INTO movie(id, title, director, rating, duration) VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128);
+INSERT INTO movie(id, title, director, rating, duration) VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100);
diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md
index 4e390c2faf..e85d8a8487 100644
--- a/persistence-modules/spring-data-jpa/README.md
+++ b/persistence-modules/spring-data-jpa/README.md
@@ -6,7 +6,6 @@
- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases)
- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories)
- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
-- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8)
- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging)
diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md
index f2553ad229..6f8d83aa9d 100644
--- a/persistence-modules/spring-hibernate4/README.md
+++ b/persistence-modules/spring-hibernate4/README.md
@@ -4,7 +4,6 @@
### Relevant Articles:
- [Guide to Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring)
-- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
- [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination)
- [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort)
- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial)
diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md
index 2f2a27e4ac..e856e4808e 100644
--- a/persistence-modules/spring-jpa/README.md
+++ b/persistence-modules/spring-jpa/README.md
@@ -4,8 +4,6 @@
### Relevant Articles:
-- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
-- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
- [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa)
- [JPA Pagination](http://www.baeldung.com/jpa-pagination)
- [Sorting with JPA](http://www.baeldung.com/jpa-sort)
diff --git a/persistence-modules/spring-persistence-simple/.gitignore b/persistence-modules/spring-persistence-simple/.gitignore
new file mode 100644
index 0000000000..83c05e60c8
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/.gitignore
@@ -0,0 +1,13 @@
+*.class
+
+#folders#
+/target
+/neoDb*
+/data
+/src/main/webapp/WEB-INF/classes
+*/META-INF/*
+
+# Packaged files #
+*.jar
+*.war
+*.ear
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md
new file mode 100644
index 0000000000..c408ff3c96
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/README.md
@@ -0,0 +1,25 @@
+=========
+
+## Spring Persistence Example Project
+
+
+### Relevant Articles:
+- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
+- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
+- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
+- [DAO with Spring and Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
+- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
+- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
+- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
+- [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate)
+
+
+### Eclipse Config
+After importing the project into Eclipse, you may see the following error:
+"No persistence xml file found in project"
+
+This can be ignored:
+- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
+Or:
+- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator
+
diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml
new file mode 100644
index 0000000000..aa9f9d5029
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/pom.xml
@@ -0,0 +1,167 @@
+
+ 4.0.0
+ spring-persistence-simple
+ 0.1-SNAPSHOT
+ spring-persistence-simple
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+ ../../
+
+
+
+
+
+ org.springframework
+ spring-orm
+ ${org.springframework.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+ org.springframework
+ spring-context
+ ${org.springframework.version}
+
+
+
+
+ org.hibernate
+ hibernate-core
+ ${hibernate.version}
+
+
+ javax.transaction
+ jta
+ ${jta.version}
+
+
+ org.hibernate
+ hibernate-entitymanager
+ ${hibernate.version}
+
+
+ mysql
+ mysql-connector-java
+ ${mysql-connector-java.version}
+ runtime
+
+
+ org.springframework.data
+ spring-data-jpa
+ ${spring-data-jpa.version}
+
+
+ com.h2database
+ h2
+ ${h2.version}
+
+
+
+ org.apache.tomcat
+ tomcat-dbcp
+ ${tomcat-dbcp.version}
+
+
+
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+
+
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+ test
+
+
+
+ org.springframework
+ spring-test
+ ${org.springframework.version}
+ test
+
+
+ com.querydsl
+ querydsl-jpa
+ ${querydsl.version}
+
+
+ com.querydsl
+ querydsl-apt
+ ${querydsl.version}
+
+
+ org.hsqldb
+ hsqldb
+ ${hsqldb.version}
+ test
+
+
+
+
+ spring-persistence-simple
+
+
+ src/main/resources
+ true
+
+
+
+
+ com.mysema.maven
+ apt-maven-plugin
+ 1.1.3
+
+
+ generate-sources
+
+ process
+
+
+ target/generated-sources
+ com.querydsl.apt.jpa.JPAAnnotationProcessor
+
+
+
+
+
+
+
+
+
+ 5.1.6.RELEASE
+
+
+ 5.4.2.Final
+ 6.0.6
+ 2.1.6.RELEASE
+ 9.0.0.M26
+ 1.1
+ 4.2.1
+ 2.4.1
+
+
+ 21.0
+ 3.5
+ 3.8.0
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java
new file mode 100644
index 0000000000..5fc932b256
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java
@@ -0,0 +1,39 @@
+package com.baeldung.hibernate.bootstrap;
+
+import com.baeldung.hibernate.bootstrap.model.TestEntity;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+public abstract class BarHibernateDAO {
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ public TestEntity findEntity(int id) {
+
+ return getCurrentSession().find(TestEntity.class, 1);
+ }
+
+ public void createEntity(TestEntity entity) {
+
+ getCurrentSession().save(entity);
+ }
+
+ public void createEntity(int id, String newDescription) {
+
+ TestEntity entity = findEntity(id);
+ entity.setDescription(newDescription);
+ getCurrentSession().save(entity);
+ }
+
+ public void deleteEntity(int id) {
+
+ TestEntity entity = findEntity(id);
+ getCurrentSession().delete(entity);
+ }
+
+ protected Session getCurrentSession() {
+ return sessionFactory.getCurrentSession();
+ }
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java
new file mode 100644
index 0000000000..150e3778af
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java
@@ -0,0 +1,61 @@
+package com.baeldung.hibernate.bootstrap;
+
+import com.google.common.base.Preconditions;
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+import org.springframework.orm.hibernate5.HibernateTransactionManager;
+import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.sql.DataSource;
+import java.util.Properties;
+
+@Configuration
+@EnableTransactionManagement
+@PropertySource({ "classpath:persistence-h2.properties" })
+public class HibernateConf {
+
+ @Autowired
+ private Environment env;
+
+ @Bean
+ public LocalSessionFactoryBean sessionFactory() {
+ final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
+ sessionFactory.setDataSource(dataSource());
+ sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.bootstrap.model" });
+ sessionFactory.setHibernateProperties(hibernateProperties());
+
+ return sessionFactory;
+ }
+
+ @Bean
+ public DataSource dataSource() {
+ final BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
+ dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
+ dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
+ dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
+
+ return dataSource;
+ }
+
+ @Bean
+ public PlatformTransactionManager hibernateTransactionManager() {
+ final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
+ transactionManager.setSessionFactory(sessionFactory().getObject());
+ return transactionManager;
+ }
+
+ private final Properties hibernateProperties() {
+ final Properties hibernateProperties = new Properties();
+ hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
+ hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
+
+ return hibernateProperties;
+ }
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java
new file mode 100644
index 0000000000..b3e979478f
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java
@@ -0,0 +1,24 @@
+package com.baeldung.hibernate.bootstrap;
+
+import com.google.common.base.Preconditions;
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.ImportResource;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+import org.springframework.orm.hibernate5.HibernateTransactionManager;
+import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import javax.sql.DataSource;
+import java.util.Properties;
+
+@Configuration
+@EnableTransactionManagement
+@ImportResource({ "classpath:hibernate5Configuration.xml" })
+public class HibernateXMLConf {
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java
new file mode 100644
index 0000000000..cae41db831
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java
@@ -0,0 +1,29 @@
+package com.baeldung.hibernate.bootstrap.model;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class TestEntity {
+
+ private int id;
+
+ private String description;
+
+ @Id
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java
new file mode 100644
index 0000000000..5a6c76a93a
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java
@@ -0,0 +1,14 @@
+package com.baeldung.persistence.dao.common;
+
+import java.io.Serializable;
+
+import com.google.common.base.Preconditions;
+
+public abstract class AbstractDao implements IOperations {
+
+ protected Class clazz;
+
+ protected final void setClazz(final Class clazzToSet) {
+ clazz = Preconditions.checkNotNull(clazzToSet);
+ }
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java
new file mode 100644
index 0000000000..e406f896dc
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java
@@ -0,0 +1,60 @@
+package com.baeldung.persistence.dao.common;
+
+import java.io.Serializable;
+import java.util.List;
+
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.google.common.base.Preconditions;
+
+@SuppressWarnings("unchecked")
+public abstract class AbstractHibernateDao extends AbstractDao implements IOperations {
+
+ @Autowired
+ protected SessionFactory sessionFactory;
+
+ // API
+
+ @Override
+ public T findOne(final long id) {
+ return (T) getCurrentSession().get(clazz, id);
+ }
+
+ @Override
+ public List findAll() {
+ return getCurrentSession().createQuery("from " + clazz.getName()).list();
+ }
+
+ @Override
+ public T create(final T entity) {
+ Preconditions.checkNotNull(entity);
+ getCurrentSession().saveOrUpdate(entity);
+ return entity;
+ }
+
+ @Override
+ public T update(final T entity) {
+ Preconditions.checkNotNull(entity);
+ return (T) getCurrentSession().merge(entity);
+ }
+
+ @Override
+ public void delete(final T entity) {
+ Preconditions.checkNotNull(entity);
+ getCurrentSession().delete(entity);
+ }
+
+ @Override
+ public void deleteById(final long entityId) {
+ final T entity = findOne(entityId);
+ Preconditions.checkState(entity != null);
+ delete(entity);
+ }
+
+ protected Session getCurrentSession() {
+ return sessionFactory.getCurrentSession();
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java
new file mode 100644
index 0000000000..18b16fa033
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java
@@ -0,0 +1,13 @@
+package com.baeldung.persistence.dao.common;
+
+import java.io.Serializable;
+
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Repository;
+
+@Repository
+@Scope(BeanDefinition.SCOPE_PROTOTYPE)
+public class GenericHibernateDao extends AbstractHibernateDao implements IGenericDao {
+ //
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java
new file mode 100644
index 0000000000..5bcebed761
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java
@@ -0,0 +1,14 @@
+package com.baeldung.persistence.dao.common;
+
+import java.io.Serializable;
+
+import org.baeldung.persistence.dao.AbstractJpaDAO;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Repository;
+
+@Repository
+@Scope(BeanDefinition.SCOPE_PROTOTYPE)
+public class GenericJpaDao extends AbstractJpaDAO implements IGenericDao {
+ //
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java
new file mode 100644
index 0000000000..8d8af18394
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java
@@ -0,0 +1,7 @@
+package com.baeldung.persistence.dao.common;
+
+import java.io.Serializable;
+
+public interface IGenericDao extends IOperations {
+ //
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java
new file mode 100644
index 0000000000..34c5e0f616
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java
@@ -0,0 +1,20 @@
+package com.baeldung.persistence.dao.common;
+
+import java.io.Serializable;
+import java.util.List;
+
+public interface IOperations {
+
+ T findOne(final long id);
+
+ List findAll();
+
+ T create(final T entity);
+
+ T update(final T entity);
+
+ void delete(final T entity);
+
+ void deleteById(final long entityId);
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java
new file mode 100644
index 0000000000..2d940527e1
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/impl/FooDao.java
@@ -0,0 +1,20 @@
+package com.baeldung.persistence.dao.impl;
+
+import org.baeldung.persistence.dao.IFooDao;
+import org.baeldung.persistence.model.Foo;
+import org.springframework.stereotype.Repository;
+
+import com.baeldung.persistence.dao.common.AbstractHibernateDao;
+
+@Repository
+public class FooDao extends AbstractHibernateDao implements IFooDao {
+
+ public FooDao() {
+ super();
+
+ setClazz(Foo.class);
+ }
+
+ // API
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/config/PersistenceConfig.java
new file mode 100644
index 0000000000..c454ab3b54
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/config/PersistenceConfig.java
@@ -0,0 +1,118 @@
+package org.baeldung.config;
+
+import java.util.Properties;
+
+import javax.sql.DataSource;
+
+import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
+import org.baeldung.persistence.dao.IFooDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.orm.hibernate5.HibernateTransactionManager;
+import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.JpaVendorAdapter;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import com.baeldung.persistence.dao.impl.FooDao;
+import com.google.common.base.Preconditions;
+
+@Configuration
+@EnableTransactionManagement
+@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager")
+@EnableJpaAuditing
+@PropertySource({ "classpath:persistence-mysql.properties" })
+@ComponentScan({ "com.baeldung.persistence" })
+public class PersistenceConfig {
+
+ @Autowired
+ private Environment env;
+
+ public PersistenceConfig() {
+ super();
+ }
+
+ @Bean
+ public LocalSessionFactoryBean sessionFactory() {
+ final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
+ sessionFactory.setDataSource(restDataSource());
+ sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
+ sessionFactory.setHibernateProperties(hibernateProperties());
+
+ return sessionFactory;
+ }
+
+ @Bean
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
+ final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
+ emf.setDataSource(restDataSource());
+ emf.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
+
+ final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
+ emf.setJpaVendorAdapter(vendorAdapter);
+ emf.setJpaProperties(hibernateProperties());
+
+ return emf;
+ }
+
+ @Bean
+ public DataSource restDataSource() {
+ final BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
+ dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
+ dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
+ dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
+
+ return dataSource;
+ }
+
+ @Bean
+ public PlatformTransactionManager hibernateTransactionManager() {
+ final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
+ transactionManager.setSessionFactory(sessionFactory().getObject());
+ return transactionManager;
+ }
+
+ @Bean
+ public PlatformTransactionManager jpaTransactionManager() {
+ final JpaTransactionManager transactionManager = new JpaTransactionManager();
+ transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
+ return transactionManager;
+ }
+
+ @Bean
+ public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
+ return new PersistenceExceptionTranslationPostProcessor();
+ }
+
+ @Bean
+ public IFooDao fooHibernateDao() {
+ return new FooDao();
+ }
+
+ private final Properties hibernateProperties() {
+ final Properties hibernateProperties = new Properties();
+ hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
+ hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
+
+ hibernateProperties.setProperty("hibernate.show_sql", "true");
+ // hibernateProperties.setProperty("hibernate.format_sql", "true");
+ // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
+
+ // Envers properties
+ hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
+
+ return hibernateProperties;
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/config/PersistenceJPAConfig.java
new file mode 100644
index 0000000000..ec0d4bca3c
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/config/PersistenceJPAConfig.java
@@ -0,0 +1,87 @@
+package org.baeldung.config;
+
+import java.util.Properties;
+
+import javax.persistence.EntityManagerFactory;
+import javax.sql.DataSource;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import com.google.common.base.Preconditions;
+
+@Configuration
+@EnableTransactionManagement
+@PropertySource({ "classpath:persistence-h2.properties" })
+@ComponentScan({ "org.baeldung.persistence" })
+@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
+public class PersistenceJPAConfig {
+
+ @Autowired
+ private Environment env;
+
+ public PersistenceJPAConfig() {
+ super();
+ }
+
+ // beans
+
+ @Bean
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
+ final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
+ em.setDataSource(dataSource());
+ em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
+
+ final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
+ em.setJpaVendorAdapter(vendorAdapter);
+ em.setJpaProperties(additionalProperties());
+
+ return em;
+ }
+
+ @Bean
+ public DataSource dataSource() {
+ final DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
+ dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
+ dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
+ dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
+
+ return dataSource;
+ }
+
+ @Bean
+ public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
+ final JpaTransactionManager transactionManager = new JpaTransactionManager();
+ transactionManager.setEntityManagerFactory(emf);
+ return transactionManager;
+ }
+
+ @Bean
+ public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
+ return new PersistenceExceptionTranslationPostProcessor();
+ }
+
+ final Properties additionalProperties() {
+ final Properties hibernateProperties = new Properties();
+ hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
+ hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
+ hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false");
+
+
+ return hibernateProperties;
+ }
+
+}
\ No newline at end of file
diff --git a/spring-all/src/main/java/org/baeldung/jdbc/CustomSQLErrorCodeTranslator.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/jdbc/CustomSQLErrorCodeTranslator.java
similarity index 100%
rename from spring-all/src/main/java/org/baeldung/jdbc/CustomSQLErrorCodeTranslator.java
rename to persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/jdbc/CustomSQLErrorCodeTranslator.java
diff --git a/spring-all/src/main/java/org/baeldung/jdbc/Employee.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/jdbc/Employee.java
similarity index 100%
rename from spring-all/src/main/java/org/baeldung/jdbc/Employee.java
rename to persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/jdbc/Employee.java
diff --git a/spring-all/src/main/java/org/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/jdbc/EmployeeDAO.java
similarity index 100%
rename from spring-all/src/main/java/org/baeldung/jdbc/EmployeeDAO.java
rename to persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/jdbc/EmployeeDAO.java
diff --git a/spring-all/src/main/java/org/baeldung/jdbc/EmployeeRowMapper.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/jdbc/EmployeeRowMapper.java
similarity index 100%
rename from spring-all/src/main/java/org/baeldung/jdbc/EmployeeRowMapper.java
rename to persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/jdbc/EmployeeRowMapper.java
diff --git a/spring-all/src/main/java/org/baeldung/jdbc/config/SpringJdbcConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/jdbc/config/SpringJdbcConfig.java
similarity index 100%
rename from spring-all/src/main/java/org/baeldung/jdbc/config/SpringJdbcConfig.java
rename to persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/jdbc/config/SpringJdbcConfig.java
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/dao/AbstractJpaDAO.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/dao/AbstractJpaDAO.java
new file mode 100644
index 0000000000..decca35c08
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/dao/AbstractJpaDAO.java
@@ -0,0 +1,47 @@
+package org.baeldung.persistence.dao;
+
+import java.io.Serializable;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+
+public abstract class AbstractJpaDAO {
+
+ private Class clazz;
+
+ @PersistenceContext
+ private EntityManager entityManager;
+
+ public final void setClazz(final Class clazzToSet) {
+ this.clazz = clazzToSet;
+ }
+
+ public T findOne(final long id) {
+ return entityManager.find(clazz, id);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List findAll() {
+ return entityManager.createQuery("from " + clazz.getName()).getResultList();
+ }
+
+ public T create(final T entity) {
+ entityManager.persist(entity);
+ return entity;
+ }
+
+ public T update(final T entity) {
+ return entityManager.merge(entity);
+ }
+
+ public void delete(final T entity) {
+ entityManager.remove(entity);
+ }
+
+ public void deleteById(final long entityId) {
+ final T entity = findOne(entityId);
+ delete(entity);
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/dao/FooDao.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/dao/FooDao.java
new file mode 100644
index 0000000000..77978c5cf2
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/dao/FooDao.java
@@ -0,0 +1,17 @@
+package org.baeldung.persistence.dao;
+
+import org.baeldung.persistence.model.Foo;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public class FooDao extends AbstractJpaDAO implements IFooDao {
+
+ public FooDao() {
+ super();
+
+ setClazz(Foo.class);
+ }
+
+ // API
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/dao/IFooDao.java
new file mode 100644
index 0000000000..ba188b9b3a
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/dao/IFooDao.java
@@ -0,0 +1,21 @@
+package org.baeldung.persistence.dao;
+
+import java.util.List;
+
+import org.baeldung.persistence.model.Foo;
+
+public interface IFooDao {
+
+ Foo findOne(long id);
+
+ List findAll();
+
+ Foo create(Foo entity);
+
+ Foo update(Foo entity);
+
+ void delete(Foo entity);
+
+ void deleteById(long entityId);
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/model/Bar.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/model/Bar.java
new file mode 100644
index 0000000000..b602e57562
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/model/Bar.java
@@ -0,0 +1,102 @@
+package org.baeldung.persistence.model;
+
+import java.io.Serializable;
+import java.util.List;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.OrderBy;
+
+@Entity
+public class Bar implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+
+ @Column(nullable = false)
+ private String name;
+
+ @OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
+ @OrderBy("name ASC")
+ List fooList;
+
+ public Bar() {
+ super();
+ }
+
+ public Bar(final String name) {
+ super();
+
+ this.name = name;
+ }
+
+ // API
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(final long id) {
+
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public List getFooList() {
+ return fooList;
+ }
+
+ public void setFooList(final List fooList) {
+ this.fooList = fooList;
+ }
+
+ //
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ final Bar other = (Bar) obj;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("Bar [name=").append(name).append("]");
+ return builder.toString();
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/model/Foo.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/model/Foo.java
new file mode 100644
index 0000000000..30635e9ef2
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/model/Foo.java
@@ -0,0 +1,104 @@
+package org.baeldung.persistence.model;
+
+import java.io.Serializable;
+
+import javax.persistence.Cacheable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.NamedNativeQueries;
+import javax.persistence.NamedNativeQuery;
+
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+
+@Entity
+@Cacheable
+@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
+@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
+public class Foo implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public Foo() {
+ super();
+ }
+
+ public Foo(final String name) {
+ super();
+
+ this.name = name;
+ }
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "ID")
+ private Long id;
+ @Column(name = "NAME")
+ private String name;
+
+ @ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER)
+ @JoinColumn(name = "BAR_ID")
+ private Bar bar;
+
+ public Bar getBar() {
+ return bar;
+ }
+
+ public void setBar(final Bar bar) {
+ this.bar = bar;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(final Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ final Foo other = (Foo) obj;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("Foo [name=").append(name).append("]");
+ return builder.toString();
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/service/FooService.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/service/FooService.java
new file mode 100644
index 0000000000..6d1bb0adbe
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/persistence/service/FooService.java
@@ -0,0 +1,36 @@
+package org.baeldung.persistence.service;
+
+import java.util.List;
+
+import org.baeldung.persistence.dao.IFooDao;
+import org.baeldung.persistence.model.Foo;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional
+public class FooService {
+
+ @Autowired
+ private IFooDao dao;
+
+ public FooService() {
+ super();
+ }
+
+ // API
+
+ public void create(final Foo entity) {
+ dao.create(entity);
+ }
+
+ public Foo findOne(final long id) {
+ return dao.findOne(id);
+ }
+
+ public List findAll() {
+ return dao.findAll();
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/config/PersistenceConfig.java
new file mode 100644
index 0000000000..067bac2018
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/config/PersistenceConfig.java
@@ -0,0 +1,85 @@
+package org.baeldung.spring.data.persistence.config;
+
+import java.util.Properties;
+
+import javax.sql.DataSource;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import com.google.common.base.Preconditions;
+
+@Configuration
+@EnableTransactionManagement
+@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" })
+@ComponentScan({ "org.baeldung.spring.data.persistence" })
+// @ImportResource("classpath*:springDataPersistenceConfig.xml")
+@EnableJpaRepositories(basePackages = "org.baeldung.spring.data.persistence.dao")
+public class PersistenceConfig {
+
+ @Autowired
+ private Environment env;
+
+ public PersistenceConfig() {
+ super();
+ }
+
+ @Bean
+ public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
+ final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
+ em.setDataSource(dataSource());
+ em.setPackagesToScan(new String[] { "org.baeldung.spring.data.persistence.model" });
+
+ final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
+ // vendorAdapter.set
+ em.setJpaVendorAdapter(vendorAdapter);
+ em.setJpaProperties(additionalProperties());
+
+ return em;
+ }
+
+ @Bean
+ public DataSource dataSource() {
+ final DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
+ dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
+ dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
+ dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
+
+ return dataSource;
+ }
+
+ @Bean
+ public PlatformTransactionManager transactionManager() {
+ final JpaTransactionManager transactionManager = new JpaTransactionManager();
+ transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
+
+ return transactionManager;
+ }
+
+ @Bean
+ public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
+ return new PersistenceExceptionTranslationPostProcessor();
+ }
+
+ final Properties additionalProperties() {
+ final Properties hibernateProperties = new Properties();
+ hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
+ hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
+ // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
+ return hibernateProperties;
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/IFooDao.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/IFooDao.java
new file mode 100644
index 0000000000..2f74096e14
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/IFooDao.java
@@ -0,0 +1,11 @@
+package org.baeldung.spring.data.persistence.dao;
+
+import org.baeldung.spring.data.persistence.model.Foo;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+public interface IFooDao extends JpaRepository {
+
+ @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
+ Foo retrieveByName(@Param("name") String name);
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/user/UserRepository.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/user/UserRepository.java
new file mode 100644
index 0000000000..4d01376af7
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/user/UserRepository.java
@@ -0,0 +1,98 @@
+package org.baeldung.spring.data.persistence.dao.user;
+
+import java.time.LocalDate;
+import java.util.Collection;
+import java.util.List;
+import java.util.stream.Stream;
+
+import org.baeldung.spring.data.persistence.model.User;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.domain.Sort;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+public interface UserRepository extends JpaRepository, UserRepositoryCustom {
+
+ Stream findAllByName(String name);
+
+ @Query("SELECT u FROM User u WHERE u.status = 1")
+ Collection findAllActiveUsers();
+
+ @Query("select u from User u where u.email like '%@gmail.com'")
+ List findUsersWithGmailAddress();
+
+ @Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
+ Collection findAllActiveUsersNative();
+
+ @Query("SELECT u FROM User u WHERE u.status = ?1")
+ User findUserByStatus(Integer status);
+
+ @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
+ User findUserByStatusNative(Integer status);
+
+ @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
+ User findUserByStatusAndName(Integer status, String name);
+
+ @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
+ User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
+
+ @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
+ User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
+
+ @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
+ User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName);
+
+ @Query("SELECT u FROM User u WHERE u.name like ?1%")
+ User findUserByNameLike(String name);
+
+ @Query("SELECT u FROM User u WHERE u.name like :name%")
+ User findUserByNameLikeNamedParam(@Param("name") String name);
+
+ @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
+ User findUserByNameLikeNative(String name);
+
+ @Query(value = "SELECT u FROM User u")
+ List findAllUsers(Sort sort);
+
+ @Query(value = "SELECT u FROM User u ORDER BY id")
+ Page findAllUsersWithPagination(Pageable pageable);
+
+ @Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
+ Page findAllUsersWithPaginationNative(Pageable pageable);
+
+ @Modifying
+ @Query("update User u set u.status = :status where u.name = :name")
+ int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
+
+ @Modifying
+ @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
+ int updateUserSetStatusForNameNative(Integer status, String name);
+
+ @Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true)
+ @Modifying
+ void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active);
+
+ @Modifying
+ @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true)
+ int updateUserSetStatusForNameNativePostgres(Integer status, String name);
+
+ @Query(value = "SELECT u FROM User u WHERE u.name IN :names")
+ List findUserByNameList(@Param("names") Collection names);
+
+ void deleteAllByCreationDateAfter(LocalDate date);
+
+ @Modifying(clearAutomatically = true, flushAutomatically = true)
+ @Query("update User u set u.active = false where u.lastLoginDate < :date")
+ void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date);
+
+ @Modifying(clearAutomatically = true, flushAutomatically = true)
+ @Query("delete User u where u.active = false")
+ int deleteDeactivatedUsers();
+
+ @Modifying(clearAutomatically = true, flushAutomatically = true)
+ @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true)
+ void addDeletedColumn();
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/user/UserRepositoryCustom.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/user/UserRepositoryCustom.java
new file mode 100644
index 0000000000..1a874fb5e5
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/user/UserRepositoryCustom.java
@@ -0,0 +1,14 @@
+package org.baeldung.spring.data.persistence.dao.user;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Predicate;
+
+import org.baeldung.spring.data.persistence.model.User;
+
+public interface UserRepositoryCustom {
+ List findUserByEmails(Set emails);
+
+ List findAllUsersByPredicates(Collection> predicates);
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/user/UserRepositoryCustomImpl.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/user/UserRepositoryCustomImpl.java
new file mode 100644
index 0000000000..c28050401c
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/dao/user/UserRepositoryCustomImpl.java
@@ -0,0 +1,57 @@
+package org.baeldung.spring.data.persistence.dao.user;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Path;
+import javax.persistence.criteria.Predicate;
+import javax.persistence.criteria.Root;
+
+import org.baeldung.spring.data.persistence.model.User;
+
+public class UserRepositoryCustomImpl implements UserRepositoryCustom {
+
+ @PersistenceContext
+ private EntityManager entityManager;
+
+ @Override
+ public List findUserByEmails(Set emails) {
+ CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+ CriteriaQuery query = cb.createQuery(User.class);
+ Root user = query.from(User.class);
+
+ Path emailPath = user.get("email");
+
+ List predicates = new ArrayList<>();
+ for (String email : emails) {
+
+ predicates.add(cb.like(emailPath, email));
+
+ }
+ query.select(user)
+ .where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
+
+ return entityManager.createQuery(query)
+ .getResultList();
+ }
+
+ @Override
+ public List findAllUsersByPredicates(Collection> predicates) {
+ List allUsers = entityManager.createQuery("select u from User u", User.class).getResultList();
+ Stream allUsersStream = allUsers.stream();
+ for (java.util.function.Predicate predicate : predicates) {
+ allUsersStream = allUsersStream.filter(predicate);
+ }
+
+ return allUsersStream.collect(Collectors.toList());
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/model/Foo.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/model/Foo.java
new file mode 100644
index 0000000000..8f316ac55b
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/model/Foo.java
@@ -0,0 +1,83 @@
+package org.baeldung.spring.data.persistence.model;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Foo implements Serializable {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+
+ @Column(nullable = false)
+ private String name;
+
+ public Foo() {
+ super();
+ }
+
+ public Foo(final String name) {
+ super();
+
+ this.name = name;
+ }
+
+ // API
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(final long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ //
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ final Foo other = (Foo) obj;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("Foo [name=").append(name).append("]");
+ return builder.toString();
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/model/Possession.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/model/Possession.java
new file mode 100644
index 0000000000..da64e78552
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/model/Possession.java
@@ -0,0 +1,86 @@
+package org.baeldung.spring.data.persistence.model;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table
+public class Possession {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private long id;
+
+ private String name;
+
+ public Possession() {
+ super();
+ }
+
+ public Possession(final String name) {
+ super();
+
+ this.name = name;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(final int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = (prime * result) + (int) (id ^ (id >>> 32));
+ result = (prime * result) + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final Possession other = (Possession) obj;
+ if (id != other.id) {
+ return false;
+ }
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]");
+ return builder.toString();
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/model/User.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/model/User.java
new file mode 100644
index 0000000000..486ed046e5
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/model/User.java
@@ -0,0 +1,132 @@
+package org.baeldung.spring.data.persistence.model;
+
+import javax.persistence.*;
+
+import java.time.LocalDate;
+import java.util.List;
+import java.util.Objects;
+
+@Entity
+@Table(name = "users")
+public class User {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private int id;
+ private String name;
+ private LocalDate creationDate;
+ private LocalDate lastLoginDate;
+ private boolean active;
+ private int age;
+ @Column(unique = true, nullable = false)
+ private String email;
+ private Integer status;
+ @OneToMany
+ List possessionList;
+
+ public User() {
+ super();
+ }
+
+ public User(String name, LocalDate creationDate,String email, Integer status) {
+ this.name = name;
+ this.creationDate = creationDate;
+ this.email = email;
+ this.status = status;
+ this.active = true;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(final int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(final String email) {
+ this.email = email;
+ }
+
+ public Integer getStatus() {
+ return status;
+ }
+
+ public void setStatus(Integer status) {
+ this.status = status;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(final int age) {
+ this.age = age;
+ }
+
+ public LocalDate getCreationDate() {
+ return creationDate;
+ }
+
+ public List getPossessionList() {
+ return possessionList;
+ }
+
+ public void setPossessionList(List possessionList) {
+ this.possessionList = possessionList;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("User [name=").append(name).append(", id=").append(id).append("]");
+ return builder.toString();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ User user = (User) o;
+ return id == user.id &&
+ age == user.age &&
+ Objects.equals(name, user.name) &&
+ Objects.equals(creationDate, user.creationDate) &&
+ Objects.equals(email, user.email) &&
+ Objects.equals(status, user.status);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, name, creationDate, age, email, status);
+ }
+
+ public LocalDate getLastLoginDate() {
+ return lastLoginDate;
+ }
+
+ public void setLastLoginDate(LocalDate lastLoginDate) {
+ this.lastLoginDate = lastLoginDate;
+ }
+
+ public boolean isActive() {
+ return active;
+ }
+
+ public void setActive(boolean active) {
+ this.active = active;
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/service/IFooService.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/service/IFooService.java
new file mode 100644
index 0000000000..26d0171551
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/service/IFooService.java
@@ -0,0 +1,11 @@
+package org.baeldung.spring.data.persistence.service;
+
+import org.baeldung.spring.data.persistence.model.Foo;
+
+import com.baeldung.persistence.dao.common.IOperations;
+
+public interface IFooService extends IOperations {
+
+ Foo retrieveByName(String name);
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/service/common/AbstractService.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/service/common/AbstractService.java
new file mode 100644
index 0000000000..cf28d5e5c6
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/service/common/AbstractService.java
@@ -0,0 +1,56 @@
+package org.baeldung.spring.data.persistence.service.common;
+
+import java.io.Serializable;
+import java.util.List;
+
+import org.springframework.data.repository.PagingAndSortingRepository;
+import org.springframework.transaction.annotation.Transactional;
+
+import com.baeldung.persistence.dao.common.IOperations;
+import com.google.common.collect.Lists;
+
+@Transactional
+public abstract class AbstractService implements IOperations {
+
+ // read - one
+
+ @Override
+ @Transactional(readOnly = true)
+ public T findOne(final long id) {
+ return getDao().findById(id).orElse(null);
+ }
+
+ // read - all
+
+ @Override
+ @Transactional(readOnly = true)
+ public List findAll() {
+ return Lists.newArrayList(getDao().findAll());
+ }
+
+ // write
+
+ @Override
+ public T create(final T entity) {
+ return getDao().save(entity);
+ }
+
+ @Override
+ public T update(final T entity) {
+ return getDao().save(entity);
+ }
+
+ @Override
+ public void delete(T entity) {
+ getDao().delete(entity);
+ }
+
+ @Override
+ public void deleteById(long entityId) {
+ T entity = findOne(entityId);
+ delete(entity);
+ }
+
+ protected abstract PagingAndSortingRepository getDao();
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/service/impl/FooService.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/service/impl/FooService.java
new file mode 100644
index 0000000000..b7ed496df1
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/spring/data/persistence/service/impl/FooService.java
@@ -0,0 +1,38 @@
+package org.baeldung.spring.data.persistence.service.impl;
+
+
+import org.baeldung.spring.data.persistence.model.Foo;
+import org.baeldung.spring.data.persistence.dao.IFooDao;
+import org.baeldung.spring.data.persistence.service.IFooService;
+import org.baeldung.spring.data.persistence.service.common.AbstractService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.repository.PagingAndSortingRepository;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional
+public class FooService extends AbstractService implements IFooService {
+
+ @Autowired
+ private IFooDao dao;
+
+ public FooService() {
+ super();
+ }
+
+ // API
+
+ @Override
+ protected PagingAndSortingRepository getDao() {
+ return dao;
+ }
+
+ // custom methods
+
+ @Override
+ public Foo retrieveByName(final String name) {
+ return dao.retrieveByName(name);
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/util/IDUtil.java b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/util/IDUtil.java
new file mode 100644
index 0000000000..85ab623e5f
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/java/org/baeldung/util/IDUtil.java
@@ -0,0 +1,33 @@
+package org.baeldung.util;
+
+import java.util.Random;
+
+public final class IDUtil {
+
+ private IDUtil() {
+ throw new AssertionError();
+ }
+
+ // API
+
+ public static String randomPositiveLongAsString() {
+ return Long.toString(randomPositiveLong());
+ }
+
+ public static String randomNegativeLongAsString() {
+ return Long.toString(randomNegativeLong());
+ }
+
+ public static long randomPositiveLong() {
+ long id = new Random().nextLong() * 10000;
+ id = (id < 0) ? (-1 * id) : id;
+ return id;
+ }
+
+ private static long randomNegativeLong() {
+ long id = new Random().nextLong() * 10000;
+ id = (id > 0) ? (-1 * id) : id;
+ return id;
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml
new file mode 100644
index 0000000000..bbb61cb3e0
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+
+
+ ${hibernate.hbm2ddl.auto}
+ ${hibernate.dialect}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml
new file mode 100644
index 0000000000..cb6cf0aa5c
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+ ${hibernate.hbm2ddl.auto}
+ ${hibernate.dialect}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/testing-modules/junit-5-configuration/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql
similarity index 100%
rename from testing-modules/junit-5-configuration/src/main/resources/jdbc/schema.sql
rename to persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql
diff --git a/testing-modules/junit-5-configuration/src/main/resources/jdbc/springJdbc-config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml
similarity index 100%
rename from testing-modules/junit-5-configuration/src/main/resources/jdbc/springJdbc-config.xml
rename to persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml
diff --git a/testing-modules/junit-5-configuration/src/main/resources/jdbc/test-data.sql b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/test-data.sql
similarity index 100%
rename from testing-modules/junit-5-configuration/src/main/resources/jdbc/test-data.sql
rename to persistence-modules/spring-persistence-simple/src/main/resources/jdbc/test-data.sql
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml b/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml
new file mode 100644
index 0000000000..ec0dc2469a
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml
@@ -0,0 +1,19 @@
+
+
+
+
+ web - %date [%thread] %-5level %logger{36} - %message%n
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-h2.properties b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-h2.properties
new file mode 100644
index 0000000000..716a96fde3
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-h2.properties
@@ -0,0 +1,13 @@
+# jdbc.X
+jdbc.driverClassName=org.h2.Driver
+jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
+jdbc.user=sa
+jdbc.pass=
+
+# hibernate.X
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.show_sql=true
+hibernate.hbm2ddl.auto=create-drop
+hibernate.cache.use_second_level_cache=true
+hibernate.cache.use_query_cache=true
+hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties
new file mode 100644
index 0000000000..b3cfd31f46
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties
@@ -0,0 +1,13 @@
+# jdbc.X
+jdbc.driverClassName=com.mysql.cj.jdbc.Driver
+jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true
+jdbc.eventGeneratedId=tutorialuser
+jdbc.pass=tutorialmy5ql
+
+# hibernate.X
+hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
+hibernate.show_sql=false
+hibernate.hbm2ddl.auto=create-drop
+
+# envers.X
+envers.audit_table_suffix=_audit_log
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml b/persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml
new file mode 100644
index 0000000000..6304fa0a65
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ${hibernate.hbm2ddl.auto}
+ ${hibernate.dialect}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/springDataPersistenceConfig.xml b/persistence-modules/spring-persistence-simple/src/main/resources/springDataPersistenceConfig.xml
new file mode 100644
index 0000000000..d6d0ec6e47
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/resources/springDataPersistenceConfig.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql b/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql
new file mode 100644
index 0000000000..9cedb75c37
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql
@@ -0,0 +1,20 @@
+DELIMITER //
+ CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255))
+ LANGUAGE SQL
+ DETERMINISTIC
+ SQL SECURITY DEFINER
+ BEGIN
+ SELECT * FROM foo WHERE name = fooName;
+ END //
+DELIMITER ;
+
+
+DELIMITER //
+ CREATE PROCEDURE GetAllFoos()
+ LANGUAGE SQL
+ DETERMINISTIC
+ SQL SECURITY DEFINER
+ BEGIN
+ SELECT * FROM foo;
+ END //
+DELIMITER ;
\ No newline at end of file
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java
new file mode 100644
index 0000000000..c41423643a
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java
@@ -0,0 +1,185 @@
+package com.baeldung.hibernate.bootstrap;
+
+import com.baeldung.hibernate.bootstrap.model.TestEntity;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.annotation.Commit;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+import org.springframework.test.context.transaction.TestTransaction;
+import org.springframework.transaction.annotation.Transactional;
+
+import static junit.framework.TestCase.assertFalse;
+import static junit.framework.TestCase.assertTrue;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { HibernateConf.class })
+@Transactional
+public class HibernateBootstrapIntegrationTest {
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ @Test
+ public void whenBootstrapHibernateSession_thenNoException() {
+
+ Session session = sessionFactory.getCurrentSession();
+
+ TestEntity newEntity = new TestEntity();
+ newEntity.setId(1);
+ session.save(newEntity);
+
+ TestEntity searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNotNull(searchEntity);
+ }
+
+ @Test
+ public void whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
+ assertTrue(TestTransaction.isActive());
+
+ //Save an entity and commit.
+ Session session = sessionFactory.getCurrentSession();
+
+ TestEntity newEntity = new TestEntity();
+ newEntity.setId(1);
+ session.save(newEntity);
+
+ TestEntity searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNotNull(searchEntity);
+ assertTrue(TestTransaction.isFlaggedForRollback());
+
+ TestTransaction.flagForCommit();
+ TestTransaction.end();
+
+ assertFalse(TestTransaction.isFlaggedForRollback());
+ assertFalse(TestTransaction.isActive());
+
+ //Check that the entity is still there in a new transaction,
+ //then delete it, but don't commit.
+ TestTransaction.start();
+
+ assertTrue(TestTransaction.isFlaggedForRollback());
+ assertTrue(TestTransaction.isActive());
+
+ session = sessionFactory.getCurrentSession();
+ searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNotNull(searchEntity);
+
+ session.delete(searchEntity);
+ session.flush();
+
+ TestTransaction.end();
+
+ assertFalse(TestTransaction.isActive());
+
+ //Check that the entity is still there in a new transaction,
+ //then delete it and commit.
+ TestTransaction.start();
+
+ session = sessionFactory.getCurrentSession();
+ searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNotNull(searchEntity);
+
+ session.delete(searchEntity);
+ session.flush();
+
+ assertTrue(TestTransaction.isActive());
+
+ TestTransaction.flagForCommit();
+ TestTransaction.end();
+
+ assertFalse(TestTransaction.isActive());
+
+ //Check that the entity is no longer there in a new transaction.
+ TestTransaction.start();
+
+ assertTrue(TestTransaction.isActive());
+
+ session = sessionFactory.getCurrentSession();
+ searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNull(searchEntity);
+ }
+
+ @Test
+ @Commit
+ public void givenTransactionCommitDefault_whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
+ assertTrue(TestTransaction.isActive());
+
+ //Save an entity and commit.
+ Session session = sessionFactory.getCurrentSession();
+
+ TestEntity newEntity = new TestEntity();
+ newEntity.setId(1);
+ session.save(newEntity);
+
+ TestEntity searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNotNull(searchEntity);
+ assertFalse(TestTransaction.isFlaggedForRollback());
+
+ TestTransaction.end();
+
+ assertFalse(TestTransaction.isFlaggedForRollback());
+ assertFalse(TestTransaction.isActive());
+
+ //Check that the entity is still there in a new transaction,
+ //then delete it, but don't commit.
+ TestTransaction.start();
+
+ assertFalse(TestTransaction.isFlaggedForRollback());
+ assertTrue(TestTransaction.isActive());
+
+ session = sessionFactory.getCurrentSession();
+ searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNotNull(searchEntity);
+
+ session.delete(searchEntity);
+ session.flush();
+
+ TestTransaction.flagForRollback();
+ TestTransaction.end();
+
+ assertFalse(TestTransaction.isActive());
+
+ //Check that the entity is still there in a new transaction,
+ //then delete it and commit.
+ TestTransaction.start();
+
+ session = sessionFactory.getCurrentSession();
+ searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNotNull(searchEntity);
+
+ session.delete(searchEntity);
+ session.flush();
+
+ assertTrue(TestTransaction.isActive());
+
+ TestTransaction.end();
+
+ assertFalse(TestTransaction.isActive());
+
+ //Check that the entity is no longer there in a new transaction.
+ TestTransaction.start();
+
+ assertTrue(TestTransaction.isActive());
+
+ session = sessionFactory.getCurrentSession();
+ searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNull(searchEntity);
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java
new file mode 100644
index 0000000000..5b811ad576
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.hibernate.bootstrap;
+
+import com.baeldung.hibernate.bootstrap.model.TestEntity;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.transaction.annotation.Transactional;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { HibernateXMLConf.class })
+@Transactional
+public class HibernateXMLBootstrapIntegrationTest {
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ @Test
+ public void whenBootstrapHibernateSession_thenNoException() {
+
+ Session session = sessionFactory.getCurrentSession();
+
+ TestEntity newEntity = new TestEntity();
+ newEntity.setId(1);
+ session.save(newEntity);
+
+ TestEntity searchEntity = session.find(TestEntity.class, 1);
+
+ Assert.assertNotNull(searchEntity);
+ }
+
+}
diff --git a/spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java
similarity index 100%
rename from spring-all/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java
rename to persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/jdbc/EmployeeDAOIntegrationTest.java
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java
new file mode 100644
index 0000000000..76c34affb9
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java
@@ -0,0 +1,157 @@
+package org.baeldung.persistence.service;
+
+import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.lessThan;
+import static org.junit.Assert.assertThat;
+
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Root;
+
+import org.baeldung.config.PersistenceJPAConfig;
+import org.baeldung.persistence.model.Foo;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
+@DirtiesContext
+public class FooPaginationPersistenceIntegrationTest {
+
+ @PersistenceContext
+ private EntityManager entityManager;
+
+ @Autowired
+ private FooService fooService;
+
+ @Before
+ public final void before() {
+ final int minimalNumberOfEntities = 25;
+ if (fooService.findAll().size() <= minimalNumberOfEntities) {
+ for (int i = 0; i < minimalNumberOfEntities; i++) {
+ fooService.create(new Foo(randomAlphabetic(6)));
+ }
+ }
+ }
+
+ // tests
+
+ @Test
+ public final void whenContextIsBootstrapped_thenNoExceptions() {
+ //
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public final void givenEntitiesExist_whenRetrievingFirstPage_thenCorrect() {
+ final int pageSize = 10;
+
+ final Query query = entityManager.createQuery("From Foo");
+ configurePagination(query, 1, pageSize);
+
+ // When
+ final List fooList = query.getResultList();
+
+ // Then
+ assertThat(fooList, hasSize(pageSize));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public final void givenEntitiesExist_whenRetrievingLastPage_thenCorrect() {
+ final int pageSize = 10;
+ final Query queryTotal = entityManager.createQuery("Select count(f.id) from Foo f");
+ final long countResult = (long) queryTotal.getSingleResult();
+
+ final Query query = entityManager.createQuery("Select f from Foo as f order by f.id");
+ final int lastPage = (int) ((countResult / pageSize) + 1);
+ configurePagination(query, lastPage, pageSize);
+ final List fooList = query.getResultList();
+
+ // Then
+ assertThat(fooList, hasSize(lessThan(pageSize + 1)));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public final void givenEntitiesExist_whenRetrievingPage_thenCorrect() {
+ final int pageSize = 10;
+
+ final Query queryIds = entityManager.createQuery("Select f.id from Foo f order by f.name");
+ final List fooIds = queryIds.getResultList();
+
+ final Query query = entityManager.createQuery("Select f from Foo as f where f.id in :ids");
+ query.setParameter("ids", fooIds.subList(0, pageSize));
+
+ final List fooList = query.getResultList();
+
+ // Then
+ assertThat(fooList, hasSize(pageSize));
+ }
+
+ @Test
+ public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenCorrect() {
+ final int pageSize = 10;
+ final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
+ final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class);
+ final Root from = criteriaQuery.from(Foo.class);
+ final CriteriaQuery select = criteriaQuery.select(from);
+ final TypedQuery typedQuery = entityManager.createQuery(select);
+ typedQuery.setFirstResult(0);
+ typedQuery.setMaxResults(pageSize);
+ final List fooList = typedQuery.getResultList();
+
+ // Then
+ assertThat(fooList, hasSize(pageSize));
+ }
+
+ @Test
+ public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenNoExceptions() {
+ int pageNumber = 1;
+ final int pageSize = 10;
+ final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
+
+ final CriteriaQuery countQuery = criteriaBuilder.createQuery(Long.class);
+ countQuery.select(criteriaBuilder.count(countQuery.from(Foo.class)));
+ final Long count = entityManager.createQuery(countQuery).getSingleResult();
+
+ final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class);
+ final Root from = criteriaQuery.from(Foo.class);
+ final CriteriaQuery select = criteriaQuery.select(from);
+
+ TypedQuery typedQuery;
+ while (pageNumber < count.intValue()) {
+ typedQuery = entityManager.createQuery(select);
+ typedQuery.setFirstResult(pageNumber - 1);
+ typedQuery.setMaxResults(pageSize);
+ System.out.println("Current page: " + typedQuery.getResultList());
+ pageNumber += pageSize;
+ }
+
+ }
+
+ // UTIL
+
+ final int determineLastPage(final int pageSize, final long countResult) {
+ return (int) (countResult / pageSize) + 1;
+ }
+
+ final void configurePagination(final Query query, final int pageNumber, final int pageSize) {
+ query.setFirstResult((pageNumber - 1) * pageSize);
+ query.setMaxResults(pageSize);
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
new file mode 100644
index 0000000000..e1b53c8ded
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java
@@ -0,0 +1,69 @@
+package org.baeldung.persistence.service;
+
+import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+
+import org.baeldung.config.PersistenceJPAConfig;
+import org.baeldung.persistence.model.Foo;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataAccessException;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.InvalidDataAccessApiUsageException;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
+@DirtiesContext
+public class FooServicePersistenceIntegrationTest {
+
+ @Autowired
+ private FooService service;
+
+ // tests
+
+ @Test
+ public final void whenContextIsBootstrapped_thenNoExceptions() {
+ //
+ }
+
+ @Test
+ public final void whenEntityIsCreated_thenNoExceptions() {
+ service.create(new Foo(randomAlphabetic(6)));
+ }
+
+ @Test(expected = DataIntegrityViolationException.class)
+ public final void whenInvalidEntityIsCreated_thenDataException() {
+ service.create(new Foo(randomAlphabetic(2048)));
+ }
+
+ @Test(expected = DataIntegrityViolationException.class)
+ public final void whenEntityWithLongNameIsCreated_thenDataException() {
+ service.create(new Foo(randomAlphabetic(2048)));
+ }
+
+ @Test(expected = InvalidDataAccessApiUsageException.class)
+ public final void whenSameEntityIsCreatedTwice_thenDataException() {
+ final Foo entity = new Foo(randomAlphabetic(8));
+ service.create(entity);
+ service.create(entity);
+ }
+
+ @Test(expected = DataAccessException.class)
+ public final void temp_whenInvalidEntityIsCreated_thenDataException() {
+ service.create(new Foo(randomAlphabetic(2048)));
+ }
+
+ @Test
+ public final void whenEntityIsCreated_thenFound() {
+ final Foo fooEntity = new Foo("abc");
+ service.create(fooEntity);
+ final Foo found = service.findOne(fooEntity.getId());
+ Assert.assertNotNull(found);
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java
new file mode 100644
index 0000000000..40249b4b30
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java
@@ -0,0 +1,118 @@
+package org.baeldung.persistence.service;
+
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Root;
+
+import org.baeldung.config.PersistenceJPAConfig;
+import org.baeldung.persistence.model.Bar;
+import org.baeldung.persistence.model.Foo;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
+@DirtiesContext
+@SuppressWarnings("unchecked")
+public class FooServiceSortingIntegrationTest {
+
+ @PersistenceContext
+ private EntityManager entityManager;
+
+ // tests
+
+ @Test
+ public final void whenSortingByOneAttributeDefaultOrder_thenPrintSortedResult() {
+ final String jql = "Select f from Foo as f order by f.id";
+ final Query sortQuery = entityManager.createQuery(jql);
+ final List fooList = sortQuery.getResultList();
+ for (final Foo foo : fooList) {
+ System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
+ }
+ }
+
+ @Test
+ public final void whenSortingByOneAttributeSetOrder_thenSortedPrintResult() {
+ final String jql = "Select f from Foo as f order by f.id desc";
+ final Query sortQuery = entityManager.createQuery(jql);
+ final List fooList = sortQuery.getResultList();
+ for (final Foo foo : fooList) {
+ System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
+ }
+ }
+
+ @Test
+ public final void whenSortingByTwoAttributes_thenPrintSortedResult() {
+ final String jql = "Select f from Foo as f order by f.name asc, f.id desc";
+ final Query sortQuery = entityManager.createQuery(jql);
+ final List fooList = sortQuery.getResultList();
+ for (final Foo foo : fooList) {
+ System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
+ }
+ }
+
+ @Test
+ public final void whenSortingFooByBar_thenBarsSorted() {
+ final String jql = "Select f from Foo as f order by f.name, f.bar.id";
+ final Query barJoinQuery = entityManager.createQuery(jql);
+ final List fooList = barJoinQuery.getResultList();
+ for (final Foo foo : fooList) {
+ System.out.println("Name:" + foo.getName());
+ if (foo.getBar() != null) {
+ System.out.print("-------BarId:" + foo.getBar().getId());
+ }
+ }
+ }
+
+ @Test
+ public final void whenSortinfBar_thenPrintBarsSortedWithFoos() {
+ final String jql = "Select b from Bar as b order by b.id";
+ final Query barQuery = entityManager.createQuery(jql);
+ final List barList = barQuery.getResultList();
+ for (final Bar bar : barList) {
+ System.out.println("Bar Id:" + bar.getId());
+ for (final Foo foo : bar.getFooList()) {
+ System.out.println("FooName:" + foo.getName());
+ }
+ }
+ }
+
+ @Test
+ public final void whenSortingFooWithCriteria_thenPrintSortedFoos() {
+ final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
+ final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class);
+ final Root from = criteriaQuery.from(Foo.class);
+ final CriteriaQuery select = criteriaQuery.select(from);
+ criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
+ final TypedQuery typedQuery = entityManager.createQuery(select);
+ final List fooList = typedQuery.getResultList();
+ for (final Foo foo : fooList) {
+ System.out.println("Name:" + foo.getName() + "--------Id:" + foo.getId());
+ }
+ }
+
+ @Test
+ public final void whenSortingFooWithCriteriaAndMultipleAttributes_thenPrintSortedFoos() {
+ final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
+ final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class);
+ final Root from = criteriaQuery.from(Foo.class);
+ final CriteriaQuery select = criteriaQuery.select(from);
+ criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")), criteriaBuilder.desc(from.get("id")));
+ final TypedQuery typedQuery = entityManager.createQuery(select);
+ final List fooList = typedQuery.getResultList();
+ for (final Foo foo : fooList) {
+ System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
+ }
+ }
+
+}
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java
new file mode 100644
index 0000000000..c530003ac1
--- /dev/null
+++ b/persistence-modules/spring-persistence-simple/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java
@@ -0,0 +1,64 @@
+package org.baeldung.persistence.service;
+
+import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.junit.Assert.assertNull;
+
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+
+import org.baeldung.config.PersistenceJPAConfig;
+import org.baeldung.persistence.model.Foo;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
+@DirtiesContext
+public class FooServiceSortingWitNullsManualIntegrationTest {
+
+ @PersistenceContext
+ private EntityManager entityManager;
+
+ @Autowired
+ private FooService service;
+
+ // tests
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public final void whenSortingByStringNullLast_thenLastNull() {
+ service.create(new Foo());
+ service.create(new Foo(randomAlphabetic(6)));
+
+ final String jql = "Select f from Foo as f order by f.name desc NULLS LAST";
+ final Query sortQuery = entityManager.createQuery(jql);
+ final List