Merge branch 'master' into bael-16656

This commit is contained in:
Josh Cummings
2019-10-26 15:37:05 -06:00
committed by GitHub
parent db85c8f275
commit 0be2175c89
20539 changed files with 1643630 additions and 0 deletions
@@ -0,0 +1,79 @@
package com.baeldung;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MongoBsonExample
{
public static void main(String[] args)
{
//
// 4.1 Connect to cluster (default is localhost:27017)
//
MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("myDB");
MongoCollection<Document> collection = database.getCollection("employees");
//
// 4.2 Insert new document
//
Document employee = new Document()
.append("first_name", "Joe")
.append("last_name", "Smith")
.append("title", "Java Developer")
.append("years_of_service", 3)
.append("skills", Arrays.asList("java", "spring", "mongodb"))
.append("manager", new Document()
.append("first_name", "Sally")
.append("last_name", "Johanson"));
collection.insertOne(employee);
//
// 4.3 Find documents
//
Document query = new Document("last_name", "Smith");
List results = new ArrayList<>();
collection.find(query).into(results);
query =
new Document("$or", Arrays.asList(
new Document("last_name", "Smith"),
new Document("first_name", "Joe")));
results = new ArrayList<>();
collection.find(query).into(results);
//
// 4.4 Update document
//
query = new Document(
"skills",
new Document(
"$elemMatch",
new Document("$eq", "spring")));
Document update = new Document(
"$push",
new Document("skills", "security"));
collection.updateMany(query, update);
//
// 4.5 Delete documents
//
query = new Document(
"years_of_service",
new Document("$lt", 0));
collection.deleteMany(query);
}
}
@@ -0,0 +1,53 @@
package com.baeldung;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
public class MongoExample {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB database = mongoClient.getDB("myMongoDb");
// print existing databases
mongoClient.getDatabaseNames().forEach(System.out::println);
database.createCollection("customers", null);
// print all collections in customers database
database.getCollectionNames().forEach(System.out::println);
// create data
DBCollection collection = database.getCollection("customers");
BasicDBObject document = new BasicDBObject();
document.put("name", "Shubham");
document.put("company", "Baeldung");
collection.insert(document);
// 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
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "John");
DBCursor cursor = collection.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
// delete data
BasicDBObject deleteQuery = new BasicDBObject();
deleteQuery.put("name", "John");
collection.remove(deleteQuery);
}
}
@@ -0,0 +1,31 @@
package com.baeldung.morphia.domain;
import java.util.List;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
@Entity
public class Author {
@Id
private String name;
private List<String> books;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getBooks() {
return books;
}
public void setBooks(List<String> books) {
this.books = books;
}
}
@@ -0,0 +1,116 @@
package com.baeldung.morphia.domain;
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;
import dev.morphia.annotations.Index;
import dev.morphia.annotations.IndexOptions;
import dev.morphia.annotations.Indexes;
import dev.morphia.annotations.Property;
import dev.morphia.annotations.Reference;
import dev.morphia.annotations.Validation;
@Entity("Books")
@Indexes({ @Index(fields = @Field("title"), options = @IndexOptions(name = "book_title")) })
@Validation("{ price : { $gt : 0 } }")
public class Book {
@Id
private String isbn;
@Property
private String title;
private String author;
@Embedded
private Publisher publisher;
@Property("price")
private double cost;
@Reference
private Set<Book> companionBooks;
public Book() {
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public double getCost() {
return cost;
}
public void addCompanionBooks(Book book) {
if (companionBooks != null)
this.companionBooks.add(book);
}
public Book(String isbn, String title, String author, double cost, Publisher publisher) {
this.isbn = isbn;
this.title = title;
this.author = author;
this.cost = cost;
this.publisher = publisher;
this.companionBooks = new HashSet<>();
}
@Override
public String toString() {
return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
long temp;
temp = Double.doubleToLongBits(cost);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((isbn == null) ? 0 : isbn.hashCode());
result = prime * result + ((publisher == null) ? 0 : publisher.hashCode());
result = prime * result + ((title == null) ? 0 : title.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;
Book other = (Book) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost))
return false;
if (isbn == null) {
if (other.isbn != null)
return false;
} else if (!isbn.equals(other.isbn))
return false;
if (publisher == null) {
if (other.publisher != null)
return false;
} else if (!publisher.equals(other.publisher))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
}
@@ -0,0 +1,70 @@
package com.baeldung.morphia.domain;
import org.bson.types.ObjectId;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
@Entity
public class Publisher {
@Id
private ObjectId id;
private String name;
public Publisher() {
}
public Publisher(ObjectId id, String name) {
this.id = id;
this.name = name;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Catalog [id=" + id + ", 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(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Publisher other = (Publisher) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
@@ -0,0 +1,142 @@
package com.baeldung.tagging;
import java.util.List;
/**
* Model for a blog post.
*
* @author Donato Rimenti
*
*/
public class Post {
/**
* Title of the post. Must be unique.
*/
private String title;
/**
* Author of the post.
*/
private String author;
/**
* Tags of the post.
*/
private List<String> tags;
/**
* Gets the {@link #title}.
*
* @return the {@link #title}
*/
public String getTitle() {
return title;
}
/**
* Sets the {@link #title}.
*
* @param title
* the new {@link #title}
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Gets the {@link #author}.
*
* @return the {@link #author}
*/
public String getAuthor() {
return author;
}
/**
* Sets the {@link #author}.
*
* @param author
* the new {@link #author}
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* Gets the {@link #tags}.
*
* @return the {@link #tags}
*/
public List<String> getTags() {
return tags;
}
/**
* Sets the {@link #tags}.
*
* @param tags
* the new {@link #tags}
*/
public void setTags(List<String> tags) {
this.tags = tags;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + ((tags == null) ? 0 : tags.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Post other = (Post) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (tags == null) {
if (other.tags != null)
return false;
} else if (!tags.equals(other.tags))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Post [title=" + title + ", author=" + author + ", tags=" + tags + "]";
}
}
@@ -0,0 +1,153 @@
package com.baeldung.tagging;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
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.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
/**
* Repository used to manage tags for a blog post.
*
* @author Donato Rimenti
*
*/
public class TagRepository implements Closeable {
/**
* Document field which holds the blog tags.
*/
private static final String TAGS_FIELD = "tags";
/**
* The post collection.
*/
private MongoCollection<Document> collection;
/**
* The MongoDB client, stored in a field in order to close it later.
*/
private MongoClient mongoClient;
/**
* Instantiates a new TagRepository by opening the DB connection.
*/
public TagRepository() {
mongoClient = new MongoClient("localhost", 27018);
MongoDatabase database = mongoClient.getDatabase("blog");
collection = database.getCollection("posts");
}
/**
* Returns a list of posts which contains one or more of the tags passed as
* argument.
*
* @param tags
* a list of tags
* @return a list of posts which contains at least one of the tags passed as
* argument
*/
public List<Post> postsWithAtLeastOneTag(String... tags) {
FindIterable<Document> results = collection.find(Filters.in(TAGS_FIELD, tags));
return StreamSupport.stream(results.spliterator(), false).map(TagRepository::documentToPost)
.collect(Collectors.toList());
}
/**
* Returns a list of posts which contains all the tags passed as argument.
*
* @param tags
* a list of tags
* @return a list of posts which contains all the tags passed as argument
*/
public List<Post> postsWithAllTags(String... tags) {
FindIterable<Document> results = collection.find(Filters.all(TAGS_FIELD, tags));
return StreamSupport.stream(results.spliterator(), false).map(TagRepository::documentToPost)
.collect(Collectors.toList());
}
/**
* Returns a list of posts which contains none of the tags passed as
* argument.
*
* @param tags
* a list of tags
* @return a list of posts which contains none of the tags passed as
* argument
*/
public List<Post> postsWithoutTags(String... tags) {
FindIterable<Document> results = collection.find(Filters.nin(TAGS_FIELD, tags));
return StreamSupport.stream(results.spliterator(), false).map(TagRepository::documentToPost)
.collect(Collectors.toList());
}
/**
* Adds a list of tags to the blog post with the given title.
*
* @param title
* the title of the blog post
* @param tags
* a list of tags to add
* @return the outcome of the operation
*/
public boolean addTags(String title, List<String> tags) {
UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title),
Updates.addEachToSet(TAGS_FIELD, tags));
return result.getModifiedCount() == 1;
}
/**
* Removes a list of tags to the blog post with the given title.
*
* @param title
* the title of the blog post
* @param tags
* a list of tags to remove
* @return the outcome of the operation
*/
public boolean removeTags(String title, List<String> tags) {
UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title),
Updates.pullAll(TAGS_FIELD, tags));
return result.getModifiedCount() == 1;
}
/**
* Utility method used to map a MongoDB document into a {@link Post}.
*
* @param document
* the document to map
* @return a {@link Post} object equivalent to the document passed as
* argument
*/
@SuppressWarnings("unchecked")
private static Post documentToPost(Document document) {
Post post = new Post();
post.setTitle(document.getString(DBCollection.ID_FIELD_NAME));
post.setAuthor(document.getString("author"));
post.setTags((List<String>) document.get(TAGS_FIELD));
return post;
}
/*
* (non-Javadoc)
*
* @see java.io.Closeable#close()
*/
@Override
public void close() throws IOException {
mongoClient.close();
}
}