Skip to content

2. Get Started

Sammwy edited this page Mar 16, 2023 · 5 revisions

Create your entity class

import com.sammwy.milkshake.Entity;

import com.sammwy.classserializer.annotations.Prop;

public class User extends Entity {
    @Prop
    public String name;

    @Prop
    public int age;
}

or

import com.sammwy.milkshake.Entity;

import com.sammwy.classserializer.annotations.Serializable;

@Serializable
public class User extends Entity {
    public String name;
    public int age;
}

Connect to Mongo Database

Provider provider = Milkshake.connect("mongodb://localhost/database_name");

Add entity repository

Repository<User> users = Milkshake.addRepository(User.class, provider, "MongoCollection"); 

Create entry

User user = new User();
user.name = "Sammwy";
user.age = 20;
user.save();

Find entry

// Find by Key
User user = users.findOne(new FindFilter("name", "Sammwy"));

// Find by Mongo ID
User user = users.findByID("<mongo_id>");

// Find many entries
List<User> users = users.findMany(new FindFilter("age", 20));

// Find all entries
List<User> users = users.findMany(new FindFilter());

Edit entry

// Edit using entity
User user = users.findOne(new FindFilter("name", "Sammwy"));
user.name = "cookie";
user.save();

// Edit using operations
users.updateOne(
    new FindFilter("name", "Sammwy"),
    new Operation().set("name", "cookie")
);

Delete entry

// Delete using entity
User user = users.findOne(new FindFilter("name", "sammwy"));
user.delete();

// Delete using find filter
users.deleteOne(new FindFilter("name", "sammwy"));

Refresh entry

If we have an entity obtained from a repository we can refresh its values using the refresh method.

User user = ...
user.refresh();