Create the model (POJO)
@Document(collection = "customer")
public class Customer {
@Id
String id;
String firstName;
String lastName;
String contact;
//getters and setters
}
Create the repository
public interface ContactRepository extends MongoRepository<Contact, String> {
public List<Customer> findByContact(String customer);
public List<Customer> findAll();
}
Note: We just need to write the interface, SpringData will take care of the implementation.
Configure MongoClient
@Configuration
public class MongoConfig extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "<dbname>";
}
@Override
public MongoClient mongoClient() {
return new MongoClient(new MongoClientURI("mongodb://<username>:<pw>@<ip>:<port>/<dbname>"));
}
}
Start using
@Autowired
private CustomerRepository customerRepository;
...
Customer c = new Customer("firstname", "lastname", "1234567890");
customerRepository.insert(contact);
List<Customer> customers = customerRepository.findAll();