I have a spring boot app with a MongoDB connection. On using the POJO/Model class with #Document(Collection = "CompanyDetails"), it successfully creates the collection in MongoDB after "POSTMAPPING" and the result goes inside the CompanyDetails collection as expected.
I have used controller, service, repository, and used the Map<String, Object> in parenthesis of the repository rather than using POJO class.
Controller:
#PostMapping("/addRecords")
public Map<String, Object> addCompanyDetails(#RequestBody Map<String, Object> companyDetails) {
return companyDetailsService.addCompanyDetails(companyDetails);
}
Service:
#Service
public class CompanyDetailsService {
#Autowired
CompanyDetailsRepository companyDetailsRepository;
public Map<String, Object> addCompanyDetails(Map<String, Object> companyDetails) {
return companyDetailsRepository.insert(companyDetails);
}
}
Repository:
#Repository
public interface CompanyDetailsRepository extends MongoRepository<Map<String, Object>, String> {}
My requirement is to create a collection without a POJO class. Because, the fields are not fixed(while inserting records). So, I can't declare fields in the POJO class & generate a getter setter.
As I'm not using the POJO class, when I POST record, it creates a collection with the name "map" & insert records inside that.
But, expected was to create "CompanyDetails" collection & store data inside that.
Yes, people using MongoDB faced this issue as MongoDB is a schemaless database and creating POJO will be difficult. So, here is the solution for such use-cases.
Firstly, you can use the MongoClient to connect with your database. Check out this document for your reference: Connect to MongoDB
Secondly, you can create databases and collections using that `mongoClient object. Check out this document for your reference Create database and collection
Finally, you can use some generic objects like HashMap or BasicDBObject to perform your CRUD operation
Related
I have the following method in a MongoDB Repository interface
#org.springframework.stereotype.Repository
public interface AnecdoteRepository extends org.springframework.data.mongodb.repository.MongoRepository<Anecdote, Long> {
#Aggregation(pipeline = { "{$sample:{size: 1}}" })
Optional<Anecdote> findRandom();
}
I have 20 records on Anecdote collection, but when I call directly this method, it returns me an empty Optional.
However, I have the same aggregation on MongoDB Compass and it returns me an only record, as I want.
Aggregation structure
Result
Should I add more records? Or what's wrong with the first pipeline in aggregation?
I'm using spring-boot-starter-data-mongodb library
I have four tables in a database. When the user uses the Search option from the React application I want the search button to query all the tables and display data from all the tables which is AWS RDS MYSQL. How should I proceed? I am using Spring boot, mysql, and react.
I would recommend taking a look at JPA Respositories. Since your db seams to be small, a simple repository method like that one should make the trick.
However, if you have a more complicated requirement, you can use a Spring Projection. Create a query that retrieves all the fields you'll need, even if they're from different tables, and map the result into a Spring Projection
Using spring data jpa you should create a method in your repository that returns a list of your projection class:
public interface MyRepository extends Repository<MyEntityProjection, Long> {
#Query("SELECT ... WHERE field = ?1")
List<MyEntityProjection> getData(String param);
}
The projection class should be something like this:
public interface MyEntityProjection {
String getField();
String getField2();
}
Adding as many fields as your query returns.
Read the docs I linked for more information and examples.
I got database with several collections in micorservice, so there's controllers which works fine. But I need to collect statistics from servers, including database. There's a good query serverStats() which gives all the information about the server, but how can I pass it through app layers?
I made interface repository extended ReactiveCrudRepository using SomeModel class as a place holder and wrote one method like String getStatistics() with #Query annotation, but it doesn't work
public interface MongoMonitoring extends ReactiveCrudRepository<SomeModel, String> {
#Query("{ serverStatus: 1 }")
String getStatus();
Use MongoTemplate. The code like:
private MongoTemplate mongoTemplate;
Document result = this.mongoTemplate.executeCommand("{ serverStatus: 1 }");
The document is from package org.bson.Document which is like JSON.
I am using a Spring web service and MongoDb to hold my data. Currently my Repository class extends MongoRepository and an obj of its interface gets injected into my Controller.
There is no method for finding and deleting a specific entity in the MongoRepository interface. How can I do this without having to provide a concrete implementation? I need to do the operation at the same time.
Here's my code on github if its useful: https://github.com/RyanNewsom/DentistAppointmentSchedulerService
I ended up figuring this one out. I made a custom class and used MongoTemplate. You can then submit a query using mongoTemplate. It contains a lot more mongo specific implementation.
#Repository
public class AppointmentCustomRepository {
#Autowired
MongoTemplate mongoTemplate;
public Appointment getAppointmentAndDelete(String id) {
return mongoTemplate.findAndRemove(Query.query(Criteria.where("id").is(id)), Appointment.class);
}
}
Sample snippet to find and delete one document in Mongo DB using Java API's
MongoCollection<Document> collection = database.getCollection("PasstheCollectionName");
Document document = collection.find.first();
Object value = document.get("_id");
Bson filter = Filter.and(Filter.eq("_id",value));
collection.findOneAndDelete(filter);
I read about ModelMapper, today and it seems to be very interesting, but I'm not sure about the right usage.
I have a Spring-Project like this:
I have my model classes which are necessary for serialization. My REST controller return DTO-objects to the front end. And my frontend returns DTOs to my controller and then I need my model objects from the DTOs to write it to the database.
I have a person class that has an attribute like: Set<Company> companies = new HashSet<Company>();
I want the modelmapper to map this set to an attribute: Set<String> companies = new HashSet<String>().The 2nd set shall be filled by calling companies.getName() instead of filling the Set with the whole object.
My questions:
Do I need a PropertyMap or a converter?
How exactly can I do this?
Is it possible to say Convert from Set<Companies> into a single String. Like I want just one company?
Sorry, I'm very new to ModelMapper and I'm searching for the best way to map during serialization and deserialization in combinatino with spring.
If the name of fields are same in both dto and bean then we can use Spring's BeanUtils class to convert the objects, as shown below:
private UserDto toDto(User user) {
UserDto dto = new UserDto();
BeanUtils.copyProperties(user, dto, new String[]{"companies"});
if (user.getCompanies() != null) {
//Iterate the list and set the company names
}
return dto;
}
BeanUtils belongs to org.springframework.beans package so no dependency is needed. We can pass the array of properties to be ignored as an argument in copyProperties method (like companies in our case) if we want to handle those by ourselves. It uses Reflections and invokes getters and setters to set the values.