Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-6128
This commit is contained in:
@@ -12,3 +12,4 @@ This module contains articles about use of Queries in Hibernate.
|
||||
- [Hibernate’s addScalar() Method](https://www.baeldung.com/hibernate-addscalar)
|
||||
- [Distinct Queries in HQL](https://www.baeldung.com/java-hql-distinct)
|
||||
- [JPA and Hibernate – Criteria vs. JPQL vs. HQL Query](https://www.baeldung.com/jpql-hql-criteria-query)
|
||||
- [Database Keywords as Columns in Hibernate Entities](https://www.baeldung.com/java-hibernate-db-keywords-as-columns)
|
||||
|
||||
@@ -79,6 +79,12 @@
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>mysql</artifactId>
|
||||
<version>${testcontainers.mysql.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
@@ -88,6 +94,7 @@
|
||||
<mysql.version>6.0.6</mysql.version>
|
||||
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
||||
<h2.version>2.1.214</h2.version>
|
||||
<testcontainers.mysql.version>1.17.6</testcontainers.mysql.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.hibernate.keywords;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "broken_phone_order")
|
||||
public class BrokenPhoneOrder implements Serializable {
|
||||
@Id
|
||||
@Column(name = "order")
|
||||
String order;
|
||||
@Column(name = "where")
|
||||
String where;
|
||||
|
||||
public BrokenPhoneOrder(String order, String where) {
|
||||
this.order = order;
|
||||
this.where = where;
|
||||
}
|
||||
|
||||
public String getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(String order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
public String getWhere() {
|
||||
return where;
|
||||
}
|
||||
|
||||
public void setWhere(String where) {
|
||||
this.where = where;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.hibernate.keywords;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "phone_order")
|
||||
public class PhoneOrder implements Serializable {
|
||||
@Id
|
||||
@Column(name = "`order`")
|
||||
String order;
|
||||
@Column(name = "`where`")
|
||||
String where;
|
||||
|
||||
public PhoneOrder(String order, String where) {
|
||||
this.order = order;
|
||||
this.where = where;
|
||||
}
|
||||
|
||||
public String getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(String order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
public String getWhere() {
|
||||
return where;
|
||||
}
|
||||
|
||||
public void setWhere(String where) {
|
||||
this.where = where;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.hibernate.keywords;
|
||||
|
||||
import static java.util.UUID.randomUUID;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class HibernateKeywordsApplicationIntegrationTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
private Session session;
|
||||
|
||||
@BeforeAll
|
||||
static void createSession() {
|
||||
sessionFactory = new Configuration().addAnnotatedClass(BrokenPhoneOrder.class)
|
||||
.addAnnotatedClass(PhoneOrder.class)
|
||||
.configure("keywords/hibernate.keywords.cfg.xml")
|
||||
.buildSessionFactory();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void before() {
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void after() {
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBrokenPhoneOrderWithReservedKeywords_whenNewObjectIsPersisted_thenItFails() {
|
||||
BrokenPhoneOrder order = new BrokenPhoneOrder(randomUUID().toString(), "My House");
|
||||
|
||||
assertThatExceptionOfType(PersistenceException.class).isThrownBy(() -> {
|
||||
session.persist(order);
|
||||
session.flush();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPhoneOrderWithEscapedKeywords_whenNewObjectIsPersisted_thenItSucceeds() {
|
||||
PhoneOrder order = new PhoneOrder(randomUUID().toString(), "here");
|
||||
|
||||
session.persist(order);
|
||||
session.flush();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version = "1.0" encoding = "utf-8"?>
|
||||
<!DOCTYPE hibernate-configuration SYSTEM
|
||||
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
||||
<hibernate-configuration>
|
||||
|
||||
<session-factory>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="connection.url">jdbc:tc:mysql:5.7.41:///restaurant?TC_INITSCRIPT=keywords/init.sql</property>
|
||||
<property name="hibernate.connection.driver_class">org.testcontainers.jdbc.ContainerDatabaseDriver</property>
|
||||
<property name="hibernate.hbm2ddl.auto">validate</property>
|
||||
<property name="show_sql">true</property>
|
||||
</session-factory>
|
||||
|
||||
</hibernate-configuration>
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE IF NOT EXISTS phone_order (
|
||||
`order` varchar(255) PRIMARY KEY,
|
||||
`where` varchar(255)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS broken_phone_order (
|
||||
`order` varchar(255) PRIMARY KEY,
|
||||
`where` varchar(255)
|
||||
);
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.mongo.insert;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.FindIterable;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoCursor;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import org.bson.BsonDocument;
|
||||
import org.bson.Document;
|
||||
import org.bson.conversions.Bson;
|
||||
|
||||
import static com.mongodb.client.model.Filters.*;
|
||||
|
||||
public class InsertFieldIntoFilter {
|
||||
|
||||
private static MongoClient mongoClient;
|
||||
private static MongoDatabase database;
|
||||
private static MongoCollection<Document> collection;
|
||||
private static String collectionName;
|
||||
private static String databaseName;
|
||||
|
||||
public static void setUp() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
|
||||
databaseName = "baeldung";
|
||||
collectionName = "pet";
|
||||
|
||||
database = mongoClient.getDatabase(databaseName);
|
||||
collection = database.getCollection(collectionName);
|
||||
}
|
||||
}
|
||||
|
||||
public static void addFieldToExistingBsonFilter() {
|
||||
|
||||
Bson existingFilter = and(eq("type", "Dog"), eq("gender", "Male"));
|
||||
|
||||
Bson newFilter = and(existingFilter, gt("age", 5));
|
||||
FindIterable<Document> documents = collection.find(newFilter);
|
||||
|
||||
MongoCursor<Document> cursor = documents.iterator();
|
||||
while (cursor.hasNext()) {
|
||||
System.out.println(cursor.next());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void addFieldToExistingBsonFilterUsingBsonDocument() {
|
||||
|
||||
Bson existingFilter = eq("type", "Dog");
|
||||
BsonDocument existingBsonDocument = existingFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
|
||||
|
||||
Bson newFilter = gt("age", 5);
|
||||
BsonDocument newBsonDocument = newFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
|
||||
|
||||
existingBsonDocument.append("age", newBsonDocument.get("age"));
|
||||
|
||||
FindIterable<Document> documents = collection.find(existingBsonDocument);
|
||||
|
||||
MongoCursor<Document> cursor = documents.iterator();
|
||||
while (cursor.hasNext()) {
|
||||
System.out.println(cursor.next());
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
|
||||
setUp();
|
||||
|
||||
addFieldToExistingBsonFilter();
|
||||
|
||||
addFieldToExistingBsonFilterUsingBsonDocument();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.mongo.insert;
|
||||
|
||||
import com.baeldung.mongo.find.FindOperationLiveTest;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoCursor;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import org.bson.BsonDocument;
|
||||
import org.bson.Document;
|
||||
import org.bson.conversions.Bson;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
import static com.mongodb.client.model.Filters.*;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class InsertFieldIntoFilterLiveTest {
|
||||
|
||||
private static MongoClient mongoClient;
|
||||
private static MongoDatabase database;
|
||||
private static MongoCollection<Document> collection;
|
||||
private static final String DATASET_JSON = "/pet.json";
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() throws IOException {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
|
||||
database = mongoClient.getDatabase("baeldung");
|
||||
collection = database.getCollection("pet");
|
||||
|
||||
collection.drop();
|
||||
|
||||
InputStream is = FindOperationLiveTest.class.getResourceAsStream(DATASET_JSON);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
|
||||
reader.lines()
|
||||
.forEach(line -> collection.insertOne(Document.parse(line)));
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPetCollection_whenFetchingAfterAddingFieldToFilter_thenFindMatchingDocuments() {
|
||||
Bson existingFilter = and(eq("type", "Dog"), eq("gender", "Male"));
|
||||
|
||||
Bson newFilter = and(existingFilter, gt("age", 5));
|
||||
MongoCursor<Document> cursor = collection.find(newFilter).iterator();
|
||||
|
||||
assertNotNull(cursor);
|
||||
assertTrue(cursor.hasNext());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPetCollection_whenFetchingAfterAddingFieldToFilterUsingBsonDocument_thenFindMatchingDocuments() {
|
||||
Bson existingFilter = eq("type", "Dog");
|
||||
BsonDocument existingBsonDocument = existingFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
|
||||
|
||||
Bson newFilter = gt("age", 5);
|
||||
BsonDocument newBsonDocument = newFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
|
||||
|
||||
existingBsonDocument.append("age", newBsonDocument.get("age"));
|
||||
MongoCursor<Document> cursor = collection.find(existingBsonDocument).iterator();
|
||||
|
||||
assertNotNull(cursor);
|
||||
assertTrue(cursor.hasNext());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{"petId":"P1","name":"Tom","age":3,"type":"Cat","gender":"Female"}
|
||||
{"petId":"P2","name":"Max","age":4,"type":"Dog","gender":"Male"}
|
||||
{"petId":"P3","name":"Milo","age":8,"type":"Dog","gender":"Male"}
|
||||
@@ -14,20 +14,14 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embedmongo</groupId>
|
||||
<artifactId>de.flapdoodle.embedmongo</artifactId>
|
||||
<version>${flapdoodle.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mongodb</groupId>
|
||||
<artifactId>mongo-java-driver</artifactId>
|
||||
<artifactId>mongodb-driver-sync</artifactId>
|
||||
<version>${mongo.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>dev.morphia.morphia</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
<artifactId>morphia-core</artifactId>
|
||||
<version>${morphia.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -42,12 +36,18 @@
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embed</groupId>
|
||||
<artifactId>de.flapdoodle.embed.mongo</artifactId>
|
||||
<version>${flapdoodle.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<mongo.version>3.12.1</mongo.version>
|
||||
<flapdoodle.version>1.11</flapdoodle.version>
|
||||
<morphia.version>1.5.3</morphia.version>
|
||||
<mongo.version>4.8.2</mongo.version>
|
||||
<flapdoodle.version>4.4.1</flapdoodle.version>
|
||||
<morphia.version>2.0.0</morphia.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,53 +1,64 @@
|
||||
package com.baeldung;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.DBCollection;
|
||||
import com.mongodb.DBCursor;
|
||||
import com.mongodb.MongoClient;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.bson.Document;
|
||||
|
||||
import com.mongodb.client.FindIterable;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoCursor;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
public class MongoExample {
|
||||
public static void main(String[] args) {
|
||||
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
|
||||
|
||||
MongoClient mongoClient = new MongoClient("localhost", 27017);
|
||||
MongoDatabase database = mongoClient.getDatabase("myMongoDb");
|
||||
|
||||
DB database = mongoClient.getDB("myMongoDb");
|
||||
// print existing databases
|
||||
mongoClient.listDatabaseNames().forEach(System.out::println);
|
||||
|
||||
// print existing databases
|
||||
mongoClient.getDatabaseNames().forEach(System.out::println);
|
||||
boolean collectionExists = mongoClient.getDatabase("myMongoDb").listCollectionNames()
|
||||
.into(new ArrayList<>()).contains("customers");
|
||||
if (!collectionExists) {
|
||||
database.createCollection("customers");
|
||||
}
|
||||
|
||||
database.createCollection("customers", null);
|
||||
// print all collections in customers database
|
||||
database.listCollectionNames().forEach(System.out::println);
|
||||
|
||||
// print all collections in customers database
|
||||
database.getCollectionNames().forEach(System.out::println);
|
||||
// create data
|
||||
MongoCollection<Document> collection = database.getCollection("customers");
|
||||
Document document = new Document();
|
||||
document.put("name", "Shubham");
|
||||
document.put("company", "Baeldung");
|
||||
collection.insertOne(document);
|
||||
|
||||
// create data
|
||||
DBCollection collection = database.getCollection("customers");
|
||||
BasicDBObject document = new BasicDBObject();
|
||||
document.put("name", "Shubham");
|
||||
document.put("company", "Baeldung");
|
||||
collection.insert(document);
|
||||
// update data
|
||||
Document query = new Document();
|
||||
query.put("name", "Shubham");
|
||||
Document newDocument = new Document();
|
||||
newDocument.put("name", "John");
|
||||
Document updateObject = new Document();
|
||||
updateObject.put("$set", newDocument);
|
||||
collection.updateOne(query, updateObject);
|
||||
|
||||
// update data
|
||||
BasicDBObject query = new BasicDBObject();
|
||||
query.put("name", "Shubham");
|
||||
BasicDBObject newDocument = new BasicDBObject();
|
||||
newDocument.put("name", "John");
|
||||
BasicDBObject updateObject = new BasicDBObject();
|
||||
updateObject.put("$set", newDocument);
|
||||
collection.update(query, updateObject);
|
||||
// read data
|
||||
Document searchQuery = new Document();
|
||||
searchQuery.put("name", "John");
|
||||
FindIterable<Document> cursor = collection.find(searchQuery);
|
||||
try (final MongoCursor<Document> cursorIterator = cursor.cursor()) {
|
||||
while (cursorIterator.hasNext()) {
|
||||
System.out.println(cursorIterator.next());
|
||||
}
|
||||
}
|
||||
|
||||
// read data
|
||||
BasicDBObject searchQuery = new BasicDBObject();
|
||||
searchQuery.put("name", "John");
|
||||
DBCursor cursor = collection.find(searchQuery);
|
||||
while (cursor.hasNext()) {
|
||||
System.out.println(cursor.next());
|
||||
// delete data
|
||||
Document deleteQuery = new Document();
|
||||
deleteQuery.put("name", "John");
|
||||
collection.deleteOne(deleteQuery);
|
||||
}
|
||||
|
||||
// delete data
|
||||
BasicDBObject deleteQuery = new BasicDBObject();
|
||||
deleteQuery.put("name", "John");
|
||||
collection.remove(deleteQuery);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
package com.baeldung.bsontojson;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import dev.morphia.annotations.Embedded;
|
||||
import dev.morphia.annotations.Entity;
|
||||
import dev.morphia.annotations.Field;
|
||||
import dev.morphia.annotations.Id;
|
||||
@@ -25,7 +23,7 @@ public class Book {
|
||||
@Property
|
||||
private String title;
|
||||
private String author;
|
||||
@Embedded
|
||||
|
||||
private Publisher publisher;
|
||||
@Property("price")
|
||||
private double cost;
|
||||
|
||||
@@ -4,8 +4,8 @@ import java.util.ArrayList;
|
||||
|
||||
import org.bson.Document;
|
||||
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
@@ -18,7 +18,7 @@ public class CollectionExistence {
|
||||
|
||||
public static void setUp() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
}
|
||||
databaseName = "baeldung";
|
||||
testCollectionName = "student";
|
||||
@@ -26,9 +26,9 @@ public class CollectionExistence {
|
||||
|
||||
public static void collectionExistsSolution() {
|
||||
|
||||
DB db = mongoClient.getDB(databaseName);
|
||||
MongoDatabase db = mongoClient.getDatabase(databaseName);
|
||||
|
||||
System.out.println("collectionName " + testCollectionName + db.collectionExists(testCollectionName));
|
||||
System.out.println("collectionName " + testCollectionName + db.listCollectionNames().into(new ArrayList<>()).contains(testCollectionName));
|
||||
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ public class CollectionExistence {
|
||||
|
||||
MongoCollection<Document> collection = database.getCollection(testCollectionName);
|
||||
|
||||
System.out.println(collection.count());
|
||||
System.out.println(collection.countDocuments());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,8 @@ import java.util.Date;
|
||||
import org.bson.Document;
|
||||
import org.bson.types.ObjectId;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
@@ -13,7 +14,7 @@ public class RetrieveIdExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try ( MongoClient mongoClient = new MongoClient("localhost", 27017) ) {
|
||||
try ( MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017") ) {
|
||||
|
||||
MongoDatabase database = mongoClient.getDatabase("myMongoDb");
|
||||
MongoCollection<Document> collection = database.getCollection("example");
|
||||
|
||||
@@ -3,7 +3,8 @@ package com.baeldung.mongo.update;
|
||||
import org.bson.Document;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.result.UpdateResult;
|
||||
@@ -16,7 +17,7 @@ public class MultipleFieldsExample {
|
||||
// Connect to cluster (default is localhost:27017)
|
||||
//
|
||||
|
||||
MongoClient mongoClient = new MongoClient("localhost", 27017);
|
||||
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
MongoDatabase database = mongoClient.getDatabase("baeldung");
|
||||
MongoCollection<Document> collection = database.getCollection("employee");
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ package com.baeldung.mongo.update;
|
||||
|
||||
import org.bson.Document;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
@@ -83,10 +84,9 @@ public class UpdateFields {
|
||||
|
||||
public static void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
database = mongoClient.getDatabase("baeldung");
|
||||
collection = database.getCollection("student");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ package com.baeldung.mongo.update;
|
||||
|
||||
import org.bson.Document;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
@@ -16,19 +17,19 @@ public class UpdateMultipleFields {
|
||||
//
|
||||
// Connect to cluster
|
||||
//
|
||||
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27007");) {
|
||||
MongoDatabase database = mongoClient.getDatabase("baeldung");
|
||||
MongoCollection<Document> collection = database.getCollection("employee");
|
||||
|
||||
MongoClient mongoClient = new MongoClient("localhost", 27007);
|
||||
MongoDatabase database = mongoClient.getDatabase("baeldung");
|
||||
MongoCollection<Document> collection = database.getCollection("employee");
|
||||
//
|
||||
// Update query
|
||||
//
|
||||
|
||||
//
|
||||
// Update query
|
||||
//
|
||||
UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
||||
|
||||
UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
||||
|
||||
System.out.println("updateResult:- " + updateResult);
|
||||
System.out.println("updateResult:- " + updateResult.getModifiedCount());
|
||||
System.out.println("updateResult:- " + updateResult);
|
||||
System.out.println("updateResult:- " + updateResult.getModifiedCount());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.baeldung.morphia.domain;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
@@ -25,7 +24,7 @@ public class Book {
|
||||
@Property
|
||||
private String title;
|
||||
private String author;
|
||||
@Embedded
|
||||
|
||||
private Publisher publisher;
|
||||
@Property("price")
|
||||
private double cost;
|
||||
|
||||
@@ -10,8 +10,9 @@ import org.bson.Document;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBCollection;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.FindIterable;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
@@ -45,7 +46,7 @@ public class TagRepository implements Closeable {
|
||||
* Instantiates a new TagRepository by opening the DB connection.
|
||||
*/
|
||||
public TagRepository() {
|
||||
mongoClient = new MongoClient("localhost", 27018);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27018");
|
||||
MongoDatabase database = mongoClient.getDatabase("blog");
|
||||
collection = database.getCollection("posts");
|
||||
}
|
||||
|
||||
@@ -2,71 +2,50 @@ package com.baeldung;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.bson.Document;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.DBCollection;
|
||||
import com.mongodb.DBCursor;
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.client.FindIterable;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoCursor;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
import de.flapdoodle.embedmongo.MongoDBRuntime;
|
||||
import de.flapdoodle.embedmongo.MongodExecutable;
|
||||
import de.flapdoodle.embedmongo.MongodProcess;
|
||||
import de.flapdoodle.embedmongo.config.MongodConfig;
|
||||
import de.flapdoodle.embedmongo.distribution.Version;
|
||||
import de.flapdoodle.embedmongo.runtime.Network;
|
||||
import de.flapdoodle.embed.mongo.distribution.Version;
|
||||
import de.flapdoodle.embed.mongo.transitions.Mongod;
|
||||
import de.flapdoodle.embed.mongo.transitions.RunningMongodProcess;
|
||||
import de.flapdoodle.reverse.TransitionWalker;
|
||||
|
||||
public class AppLiveTest {
|
||||
|
||||
private static final String DB_NAME = "myMongoDb";
|
||||
private MongodExecutable mongodExe;
|
||||
private MongodProcess mongod;
|
||||
private Mongo mongo;
|
||||
private DB db;
|
||||
private DBCollection collection;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
// Creating Mongodbruntime instance
|
||||
MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance();
|
||||
|
||||
// Creating MongodbExecutable
|
||||
mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345, Network.localhostIsIPv6()));
|
||||
|
||||
// Starting Mongodb
|
||||
mongod = mongodExe.start();
|
||||
mongo = new Mongo("localhost", 12345);
|
||||
|
||||
// Creating DB
|
||||
db = mongo.getDB(DB_NAME);
|
||||
|
||||
// Creating collection Object and adding values
|
||||
collection = db.getCollection("customers");
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() throws Exception {
|
||||
mongod.stop();
|
||||
mongodExe.cleanup();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddressPersistance() {
|
||||
BasicDBObject contact = new BasicDBObject();
|
||||
contact.put("name", "John");
|
||||
contact.put("company", "Baeldung");
|
||||
try (TransitionWalker.ReachedState<RunningMongodProcess> running = Mongod.instance().start(Version.V6_0_3)) {
|
||||
try (MongoClient mongo = MongoClients.create("mongodb://" + running.current().getServerAddress().getHost() + ":" + running.current().getServerAddress().getPort())) {
|
||||
// Creating DB
|
||||
MongoDatabase db = mongo.getDatabase(DB_NAME);
|
||||
|
||||
// Inserting document
|
||||
collection.insert(contact);
|
||||
DBCursor cursorDoc = collection.find();
|
||||
BasicDBObject contact1 = new BasicDBObject();
|
||||
while (cursorDoc.hasNext()) {
|
||||
contact1 = (BasicDBObject) cursorDoc.next();
|
||||
System.out.println(contact1);
|
||||
// Creating collection Object and adding values
|
||||
MongoCollection<Document> collection = db.getCollection("customers");
|
||||
|
||||
Document contact = new Document();
|
||||
contact.put("name", "John");
|
||||
contact.put("company", "Baeldung");
|
||||
|
||||
// Inserting document
|
||||
collection.insertOne(contact);
|
||||
FindIterable<Document> cursorDoc = collection.find();
|
||||
Document contact1 = new Document();
|
||||
final MongoCursor<Document> cursor = cursorDoc.cursor();
|
||||
while (cursor.hasNext()) {
|
||||
contact1 = cursor.next();
|
||||
System.out.println(contact1);
|
||||
}
|
||||
assertEquals(contact1.get("name"), "John");
|
||||
}
|
||||
}
|
||||
assertEquals(contact1.get("name"), "John");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.baeldung.bsontojson;
|
||||
|
||||
import static dev.morphia.query.experimental.filters.Filters.eq;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@@ -14,10 +15,12 @@ import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
import dev.morphia.Datastore;
|
||||
import dev.morphia.DeleteOptions;
|
||||
import dev.morphia.Morphia;
|
||||
|
||||
public class BsonToJsonLiveTest {
|
||||
@@ -27,9 +30,8 @@ public class BsonToJsonLiveTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
Morphia morphia = new Morphia();
|
||||
morphia.mapPackage("com.baeldung.bsontojson");
|
||||
datastore = morphia.createDatastore(new MongoClient(), DB_NAME);
|
||||
datastore = Morphia.createDatastore(MongoClients.create(), DB_NAME);
|
||||
datastore.getMapper().mapPackage("com.baeldung.bsontojson");
|
||||
datastore.ensureIndexes();
|
||||
|
||||
datastore.save(new Book()
|
||||
@@ -44,25 +46,33 @@ public class BsonToJsonLiveTest {
|
||||
|
||||
@AfterClass
|
||||
public static void tearDown() {
|
||||
datastore.delete(datastore.createQuery(Book.class));
|
||||
datastore.find(Book.class)
|
||||
.filter(eq("isbn", "isbn"))
|
||||
.filter(eq("title", "title"))
|
||||
.filter(eq("author", "author"))
|
||||
.filter(eq("cost", "3.95"))
|
||||
.delete(new DeleteOptions().multi(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() {
|
||||
|
||||
String json;
|
||||
try (MongoClient mongoClient = new MongoClient()) {
|
||||
try (MongoClient mongoClient = MongoClients.create()) {
|
||||
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
|
||||
Document bson = mongoDatabase.getCollection("Books").find().first();
|
||||
json = bson.toJson();
|
||||
json = bson.toJson(JsonWriterSettings
|
||||
.builder()
|
||||
.dateTimeConverter(new JSONDateFormatEpochTimeConverter())
|
||||
.build());
|
||||
}
|
||||
|
||||
String expectedJson = "{\"_id\": \"isbn\", " +
|
||||
"\"className\": \"com.baeldung.bsontojson.Book\", " +
|
||||
"\"_t\": \"Book\", " +
|
||||
"\"title\": \"title\", " +
|
||||
"\"author\": \"author\", " +
|
||||
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
|
||||
"\"name\": \"publisher\"}, " +
|
||||
"\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
|
||||
"\"price\": 3.95, " +
|
||||
"\"publishDate\": {\"$date\": 1577898812000}}";
|
||||
|
||||
@@ -71,12 +81,11 @@ public class BsonToJsonLiveTest {
|
||||
assertEquals(expectedJson, json);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() {
|
||||
|
||||
String json;
|
||||
try (MongoClient mongoClient = new MongoClient()) {
|
||||
try (MongoClient mongoClient = MongoClients.create()) {
|
||||
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
|
||||
Document bson = mongoDatabase.getCollection("Books").find().first();
|
||||
json = bson.toJson(JsonWriterSettings
|
||||
@@ -86,11 +95,11 @@ public class BsonToJsonLiveTest {
|
||||
}
|
||||
|
||||
String expectedJson = "{\"_id\": \"isbn\", " +
|
||||
"\"className\": \"com.baeldung.bsontojson.Book\", " +
|
||||
"\"_t\": \"Book\", " +
|
||||
"\"title\": \"title\", " +
|
||||
"\"author\": \"author\", " +
|
||||
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
|
||||
"\"name\": \"publisher\"}, " +
|
||||
"\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
|
||||
"\"price\": 3.95, " +
|
||||
"\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}";
|
||||
|
||||
@@ -103,7 +112,7 @@ public class BsonToJsonLiveTest {
|
||||
public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() {
|
||||
|
||||
String json;
|
||||
try (MongoClient mongoClient = new MongoClient()) {
|
||||
try (MongoClient mongoClient = MongoClients.create()) {
|
||||
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
|
||||
Document bson = mongoDatabase.getCollection("Books").find().first();
|
||||
json = bson.toJson(JsonWriterSettings
|
||||
@@ -113,11 +122,11 @@ public class BsonToJsonLiveTest {
|
||||
}
|
||||
|
||||
String expectedJson = "{\"_id\": \"isbn\", " +
|
||||
"\"className\": \"com.baeldung.bsontojson.Book\", " +
|
||||
"\"_t\": \"Book\", " +
|
||||
"\"title\": \"title\", " +
|
||||
"\"author\": \"author\", " +
|
||||
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
|
||||
"\"name\": \"publisher\"}, " +
|
||||
"\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
|
||||
"\"price\": 3.95, " +
|
||||
"\"publishDate\": \"2020-01-01T17:13:32Z\"}";
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.bsontojson;
|
||||
|
||||
import org.bson.json.Converter;
|
||||
import org.bson.json.StrictJsonWriter;
|
||||
|
||||
/**
|
||||
* Convertor to epoch time
|
||||
*/
|
||||
public class JSONDateFormatEpochTimeConverter implements Converter<Long> {
|
||||
|
||||
@Override
|
||||
public void convert(Long value, StrictJsonWriter writer) {
|
||||
writer.writeStartObject();
|
||||
writer.writeName("$date");
|
||||
writer.writeNumber(String.valueOf(value));
|
||||
writer.writeEndObject();
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ import org.bson.Document;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
@@ -22,7 +22,7 @@ public class CollectionExistenceLiveTest {
|
||||
@Before
|
||||
public void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
databaseName = "baeldung";
|
||||
testCollectionName = "student";
|
||||
|
||||
@@ -58,28 +58,16 @@ public class CollectionExistenceLiveTest {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionExists_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||
|
||||
DB db = mongoClient.getDB(databaseName);
|
||||
Boolean collectionStatus = db.collectionExists(testCollectionName);
|
||||
|
||||
Boolean expectedStatus = true;
|
||||
assertEquals(expectedStatus, collectionStatus);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListCollectionNames_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
boolean collectionExists = database.listCollectionNames()
|
||||
.into(new ArrayList<String>())
|
||||
.into(new ArrayList<>())
|
||||
.contains(testCollectionName);
|
||||
|
||||
Boolean expectedStatus = true;
|
||||
assertEquals(expectedStatus, collectionExists);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -88,7 +76,7 @@ public class CollectionExistenceLiveTest {
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
|
||||
MongoCollection<Document> collection = database.getCollection(testCollectionName);
|
||||
Boolean collectionExists = collection.count() > 0 ? true : false;
|
||||
Boolean collectionExists = collection.countDocuments() > 0 ? true : false;
|
||||
|
||||
Boolean expectedStatus = false;
|
||||
assertEquals(expectedStatus, collectionExists);
|
||||
|
||||
@@ -2,39 +2,44 @@ package com.baeldung.morphia;
|
||||
|
||||
import static dev.morphia.aggregation.Group.grouping;
|
||||
import static dev.morphia.aggregation.Group.push;
|
||||
import static dev.morphia.query.experimental.filters.Filters.eq;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.bson.types.ObjectId;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.morphia.domain.Author;
|
||||
import com.baeldung.morphia.domain.Book;
|
||||
import com.baeldung.morphia.domain.Publisher;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.model.ReturnDocument;
|
||||
|
||||
import dev.morphia.Datastore;
|
||||
import dev.morphia.DeleteOptions;
|
||||
import dev.morphia.ModifyOptions;
|
||||
import dev.morphia.Morphia;
|
||||
import dev.morphia.query.FindOptions;
|
||||
import dev.morphia.query.Query;
|
||||
import dev.morphia.query.UpdateOperations;
|
||||
import dev.morphia.query.experimental.updates.UpdateOperators;
|
||||
|
||||
@Ignore
|
||||
public class MorphiaIntegrationTest {
|
||||
|
||||
private static Datastore datastore;
|
||||
private static ObjectId id = new ObjectId();
|
||||
|
||||
@BeforeClass
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
Morphia morphia = new Morphia();
|
||||
morphia.mapPackage("com.baeldung.morphia");
|
||||
datastore = morphia.createDatastore(new MongoClient(), "library");
|
||||
datastore = Morphia.createDatastore(MongoClients.create(), "library");
|
||||
datastore.getMapper().mapPackage("com.baeldung.morphia");
|
||||
datastore.ensureIndexes();
|
||||
}
|
||||
|
||||
@@ -47,11 +52,11 @@ public class MorphiaIntegrationTest {
|
||||
datastore.save(companionBook);
|
||||
datastore.save(book);
|
||||
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.find()
|
||||
.toList();
|
||||
Query<Book> booksQuery = datastore.find(Book.class)
|
||||
.filter(eq("title", "Learning Java"));
|
||||
List<Book> books = StreamSupport
|
||||
.stream(booksQuery.spliterator(), true)
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(1, books.size());
|
||||
assertEquals(book, books.get(0));
|
||||
}
|
||||
@@ -61,19 +66,13 @@ public class MorphiaIntegrationTest {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
|
||||
datastore.save(book);
|
||||
Query<Book> query = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java");
|
||||
UpdateOperations<Book> updates = datastore.createUpdateOperations(Book.class)
|
||||
.inc("price", 1);
|
||||
datastore.update(query, updates);
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.find()
|
||||
.toList();
|
||||
assertEquals(4.95, books.get(0)
|
||||
.getCost());
|
||||
|
||||
final Book execute = datastore.find(Book.class)
|
||||
.filter(eq("title", "Learning Java"))
|
||||
.modify(UpdateOperators.set("price", 4.95))
|
||||
.execute(new ModifyOptions().returnDocument(ReturnDocument.AFTER));
|
||||
|
||||
assertEquals(4.95, execute.getCost());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -81,16 +80,12 @@ public class MorphiaIntegrationTest {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
|
||||
datastore.save(book);
|
||||
Query<Book> query = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java");
|
||||
datastore.delete(query);
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.find()
|
||||
.toList();
|
||||
assertEquals(0, books.size());
|
||||
datastore.find(Book.class)
|
||||
.filter(eq("title", "Learning Java"))
|
||||
.delete(new DeleteOptions().multi(true));
|
||||
Query<Book> books = datastore.find(Book.class)
|
||||
.filter(eq("title", "Learning Java"));
|
||||
assertFalse(books.iterator().hasNext());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -107,7 +102,6 @@ public class MorphiaIntegrationTest {
|
||||
.out(Author.class);
|
||||
|
||||
assertTrue(authors.hasNext());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -115,17 +109,12 @@ public class MorphiaIntegrationTest {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
|
||||
datastore.save(book);
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.project("title", true)
|
||||
.find()
|
||||
.toList();
|
||||
assertEquals(books.size(), 1);
|
||||
assertEquals("Learning Java", books.get(0)
|
||||
.getTitle());
|
||||
assertNull(books.get(0)
|
||||
.getAuthor());
|
||||
List<Book> books = datastore.find(Book.class)
|
||||
.filter(eq("title", "Learning Java"))
|
||||
.iterator(new FindOptions().projection().include("title")).toList();
|
||||
assertEquals( 1, books.size());
|
||||
assertEquals("Learning Java", books.get(0).getTitle());
|
||||
assertNull(books.get(0).getAuthor());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -100,9 +100,7 @@ public class TaggingLiveTest {
|
||||
results.forEach(System.out::println);
|
||||
|
||||
Assert.assertEquals(1, results.size());
|
||||
results.forEach(post -> {
|
||||
Assert.assertFalse(post.getTags().contains("MongoDB"));
|
||||
});
|
||||
results.forEach(post -> Assert.assertFalse(post.getTags().contains("MongoDB")));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,7 +8,8 @@ import org.bson.Document;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
@@ -27,7 +28,7 @@ public class UpdateFieldLiveTest {
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
db = mongoClient.getDatabase("baeldung");
|
||||
collection = db.getCollection("student");
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
@@ -23,7 +24,7 @@ public class UpdateMultipleFieldsLiveTest {
|
||||
@Before
|
||||
public void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
mongoClient = MongoClients.create("mongodb://localhost:27017");
|
||||
db = mongoClient.getDatabase("baeldung");
|
||||
collection = db.getCollection("employee");
|
||||
|
||||
|
||||
@@ -43,7 +43,8 @@
|
||||
<module>java-jpa</module> <!-- long running -->
|
||||
<module>java-jpa-2</module> <!-- long running -->
|
||||
<module>java-jpa-3</module>
|
||||
<module>java-mongodb</module> <!-- long running -->
|
||||
<!-- enable it when persistence-modules is migrated to JDK9+ -->
|
||||
<!-- <module>java-mongodb</module>--> <!-- long running -->
|
||||
<module>java-mongodb-2</module> <!-- long running -->
|
||||
<module>java-mongodb-3</module> <!-- long running -->
|
||||
<module>java-mongodb-queries</module> <!-- long running -->
|
||||
|
||||
2
persistence-modules/rethinkdb/README.md
Normal file
2
persistence-modules/rethinkdb/README.md
Normal file
@@ -0,0 +1,2 @@
|
||||
## Relevant Articles
|
||||
- [Getting Started With RethinkDB](https://www.baeldung.com/rethinkdb)
|
||||
@@ -1,3 +1,4 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Using Test Containers With Spring Data Cassandra](https://www.baeldung.com/spring-data-cassandra-test-containers)
|
||||
- [Cassandra – Object Mapping with DataStax Java Driver](https://www.baeldung.com/cassandra-object-mapping-datastax-java-driver)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.spring.data.persistence.truncate;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
|
||||
@Repository
|
||||
public class EntityManagerRepository {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Transactional
|
||||
public void truncateTable(String tableName) {
|
||||
String sql = "TRUNCATE TABLE " + tableName;
|
||||
Query query = entityManager.createNativeQuery(sql);
|
||||
query.executeUpdate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.spring.data.persistence.truncate;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Repository
|
||||
public class JdbcTemplateRepository {
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public JdbcTemplateRepository(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void truncateTable(String tableName) {
|
||||
String sql = "TRUNCATE TABLE " + tableName;
|
||||
jdbcTemplate.execute(sql);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.spring.data.persistence.truncate;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = MyEntity.TABLE_NAME)
|
||||
public class MyEntity {
|
||||
|
||||
public final static String TABLE_NAME = "my_entity";
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
MyEntity myEntity = (MyEntity) o;
|
||||
return Objects.equals(id, myEntity.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MyEntity{" +
|
||||
"id=" + id +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.spring.data.persistence.truncate;
|
||||
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
@Repository
|
||||
public interface MyEntityRepository extends CrudRepository<MyEntity, Long> {
|
||||
|
||||
@Modifying
|
||||
@Transactional
|
||||
// need to wrap in double quotes due to
|
||||
// spring.jpa.properties.hibernate.globally_quoted_identifiers=true backward compatibility
|
||||
// property disabled in tests
|
||||
@Query(value = "truncate table " + MyEntity.TABLE_NAME, nativeQuery = true)
|
||||
void truncateTable();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.spring.data.persistence.truncate;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
|
||||
@EntityScan(basePackageClasses = MyEntity.class)
|
||||
@SpringBootApplication
|
||||
public class TruncateSpringBootApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(TruncateSpringBootApplication.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.spring.data.persistence.truncate;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest(classes = TruncateSpringBootApplication.class,
|
||||
properties = "spring.jpa.properties.hibernate.globally_quoted_identifiers=false")
|
||||
class TruncateIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private MyEntityRepository myEntityRepository;
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplateRepository jdbcTemplateRepository;
|
||||
|
||||
@Autowired
|
||||
private EntityManagerRepository entityManagerRepository;
|
||||
|
||||
@Test
|
||||
void givenSomeData_whenRepositoryTruncateDate_thenNoDataLeft() {
|
||||
int givenCount = 3;
|
||||
givenDummyData(givenCount);
|
||||
|
||||
myEntityRepository.truncateTable();
|
||||
|
||||
assertThat(myEntityRepository.count())
|
||||
.isNotEqualTo(givenCount)
|
||||
.isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSomeData_whenEntityManagerTruncateDate_thenNoDataLeft() {
|
||||
int givenCount = 3;
|
||||
givenDummyData(givenCount);
|
||||
|
||||
entityManagerRepository.truncateTable(MyEntity.TABLE_NAME);
|
||||
|
||||
assertThat(myEntityRepository.count())
|
||||
.isNotEqualTo(givenCount)
|
||||
.isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSomeData_whenJDBCTemplateTruncateDate_thenNoDataLeft() {
|
||||
int givenCount = 3;
|
||||
givenDummyData(givenCount);
|
||||
|
||||
jdbcTemplateRepository.truncateTable(MyEntity.TABLE_NAME);
|
||||
|
||||
assertThat(myEntityRepository.count())
|
||||
.isNotEqualTo(givenCount)
|
||||
.isZero();
|
||||
}
|
||||
|
||||
private void givenDummyData(int count) {
|
||||
List<MyEntity> input = Stream.generate(this::givenMyEntity).limit(count).collect(Collectors.toList());
|
||||
myEntityRepository.saveAll(input);
|
||||
}
|
||||
|
||||
private MyEntity givenMyEntity() {
|
||||
return new MyEntity();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
ds.type=javax.sql.DataSource
|
||||
ds.driver=org.h2.Driver
|
||||
ds.url=jdbc:jdbc:h2:mem:testdb
|
||||
ds.url=jdbc:h2:mem:testdb
|
||||
ds.user=sa
|
||||
ds.password=password
|
||||
|
||||
@@ -21,7 +21,7 @@ public class SimpleJNDIUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenMockJndiDataSource_thenReturnJndiDataSource() throws Exception {
|
||||
String dsString = "org.h2.Driver::::jdbc:jdbc:h2:mem:testdb::::sa";
|
||||
String dsString = "org.h2.Driver::::jdbc:h2:mem:testdb::::sa";
|
||||
Context envContext = (Context) this.initContext.lookup("java:/comp/env");
|
||||
DataSource ds = (DataSource) envContext.lookup("datasource/ds");
|
||||
|
||||
|
||||
Reference in New Issue
Block a user