how to delete qa database older than 2 months in mongodb using reactivemongorepository - reactive-programming

I want to delete QA database older than 2 months in mongodb using reactiveMongoRepository using spring web flux, how can I do that, do I have to create a custom query a custom method can work. I have class in which particular fields are there
class A { private String Id;
private String title;
private Instant startTime;
private Instant endTime;
}
I am not getting idea how to work on that

Related

#CreationTimestamp in Hibernate is storing wrong date in database

I have used hibernate #CreationTimestamp (import org.hibernate.annotations.CreationTimestamp;) in my spring boot project for the field private Date createdDate;
and Date is of import java.util.Date; to store the default current timestamp. This date is not having any setter method in java code.
I am using PostgreSQL 9.5.4 version and when I save, the created date is saved as 28th October 2022 but the correct created date which should have been stored is 23rd January 2023. But #UpdateTimestamp is working correctly. The picture from the database depicts the same.
#Entity
#Audited
public class EntityClassName implements Serializable{
private static final long serialVersionUID = 6004021640401026397L;
...
private String createdBy;
#CreationTimestamp
private Date createdDate;
private String updatedBy;
#UpdateTimestamp
private Date updatedDate;
}
Update 1:
So when I use #Temporal(TemporalType.TIMESTAMP) it stores the correct date in the database. Please find below code snippet:
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
But in the same database schema for other tables, I haven't used #Temporal(TemporalType.TIMESTAMP) and it is still working fine and storing the correct date in the database.
Can someone please guide what is going wrong here? Appreciate your help

Storing logging data to MongoDB with Spring Boot

I have a specific requirement needed in my project is to store logging data in my MongoDB database. There are lots of blogs for storing logs in a relational database but I can't find anything that works with MongoDB.
After hours of searching, I found this Wordpress article but after implementing it nothing happened. Blog: https://assylias.wordpress.com/2013/03/22/a-simple-logback-appender-for-mongodb/?unapproved=1424&moderation-hash=a5ff2a0d2832b77e2d7c0be3173ea667#comment-1424
But it's not working
Problem: I need to persist the log data to MongoDB.
Does anyone know how to append log data into MongoDB with Spring Boot?
Edit: I've figured a way around how to do it but it can be done with any type of database no matter MySQL or MongoDB. I'm providing the answer to how I did it but the question is still open. If anyone knows how to do it feel free to answer it and if it works I will accept the answer.
So the trick here is making a custom method that returns a string to the Logger class and saves the data to the database(any database relational or NoSQL doesn't matter).
I will try to explain the whole scenario:
This is a document that will store the data to the MongoDB
#Document
public class Logs {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
private Date date;
private String level;
private String message;
//getters and setters
}
If you are using MySQL you can use #Entity. Then create a MongoRepository of this class or CrudRepository if using JPA
public interface LogsRepository extends MongoRepository<Logs, String> {
}
Now you have to make a CustomLogger class which is used to insert data to the database
#Component
public class CustomLogger{
#Autowired
MongoTemplate mongoTemplate;
public String info(String message) {
Logs logs = new Logs();
logs.setLevel("INFO");
logs.setMessage(message);
logs.setDate(new Date());
mongoTemplate.insert(loggerDetail);
return message;
// same for other methods like debug(), error(), etc
}
Here I used MongoTemplate instead of LogsRepostiry to save data because Mongo allow to insert data if extends MongoRepository of every class
Now all you have to do is autowire this component to the class where you are using the logger. For my case it was a controller. When I'm hitting an API logs will show in console and also will save to the database
#RestController
public class LogsController {
#Autowired
CustomLogger customLogger;
Logger logger = LoggerFactory.getLogger(CustomLogger.class);
#GetMapping("/logger")
public String basicControllerToSaveData() {
logger.info(customLogger.info("Saving Logs to database"));
return "Success";
}
}
This will do the trick!

Getting multiple values from Aerospike with SpringData

I want to fetch multiple data using Aerospike Repositories. I have defined a method:
List<Profile> findByIds(List<String> profilekeys, Class<Profile> class1);
And trying to use it as:
profileRepository.findByIds(profilekeys, Profile.class);
The Profile is:
#Id
private String id;
private String obj;
But, I am getting issues like:
No property ids found for type Profile! Did you mean 'id'?
How can I solve the issue?

Document in MongoRepository not deleted with 'expireAfterSeconds'

I would like my MongoRepository in Spring Boot to automatically delete documents at a certain point in time after creation. Therefore I created the following class:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
public class MyDocument {
#Id
private String id;
#Indexed
private String name;
#Indexed(expireAfterSeconds = 0)
private LocalDateTime deleteAt;
}
Then, I save it in the Spring Boot MongoRepository:
MyDocument doc = modelMapper.map(myDocumentDto, MyDocument.class);
LocalDateTime timePoint = LocalDateTime.now();
timePoint = timePoint.plusMinutes(1L);
doc.setDeleteAt(timePoint);
docRepository.save(doc);
I periodically query the repository and would assume that after one minute, the document will not be there anymore. Unfortunately, I get the document every time I query and it is never deleted.
What am I doing wrong?
The document is persisted as follows (.toString()):
MyDocument{id='5915c65a2e9b694ac8ff8b67', name='string', deleteAt=2017-05-12T16:28:38.787}
Is MongoDB possibly unable to read and process the LocalDateTime format? I'm using org.springframework.data:spring-data-mongodb:1.10.1.RELEASE, so JSR-310 should already be supported as announced in 2015 here: https://spring.io/blog/2015/03/26/what-s-new-in-spring-data-fowler
I could fix the issue:
First of all, java.time.LocalDateTime is no problem with Spring Data / MongoDB.
For clarification, add a name to an index, e.g. #Indexed(name = "deleteAt", expireAfterSeconds = 0). This step might not be needed though. However, adding the #Document annotation helped a lot:
#Document(collection = "expiringDocument")
When I delete the whole collection while my application is running, a new document insert will create the collection again but without the indexes. To ensure indexes are created, restart the application.

How to properly use Locking or Transactions to prevent duplicates using Spring Data

What is the best way to check if a record exists and if it doesn't, create it (avoiding duplicates)?
Keep in mind that this is a distributed application running across many application servers.
I'm trying to avoid these:
Race Conditions
TOCTOU
A simple example:
Person.java
#Entity
public class Person {
#Id
#GeneratedValue
private long id;
private String firstName;
private String lastName;
//Getters and Setters Omitted
}
PersonRepository.java
public interface PersonRepository extends CrudRepository<Person, Long>{
public Person findByFirstName(String firstName);
}
Some Method
public void someMethod() {
Person john = new Person();
john.setFirstName("John");
john.setLastName("Doe");
if(personRepo.findByFirstName(john.getFirstName()) == null){
personRepo.save(john);
}else{
//Don't Save Person
}
}
Clearly as the code currently stands, there is a chance that the Person could be inserted in the database in between the time I checked if it already exists and when I insert it myself. Thus a duplicate would be created.
How should I avoid this?
Based on my initial research, perhaps a combination of
#Transactional
#Lock
But the exact configuration is what I'm unsure of. Any guidance would be greatly appreciated. To reiterate, this application will be distributed across multiple servers so this must still work in a highly-available, distributed environment.
For Inserts: if you want to prevent same recordsto be persisted, than you may want to take some precoutions on DB side. In your example, if firstname should be unique, then define a unique index on that column, or a agroup of colunsd that should be unique, and let the DB handle the check, you just insert & get exception if you're inserting a record that's already inserted.
For updates: use #Version (javax.persistence.Version) annotation like this:
#Version
private long version;
Define a version column in tables, Hibernate or any other ORM will automatically populate the value & also verison to where clause when entity updated. So if someone try to update the old entity, it prevent this. Be careful, this doesn't throw exception, just return update count as 0, so you may want to check this.