- Spring Security(Third Edition)
- Mick Knutson Robert Winch Peter Mularien
- 205字
- 2025-04-04 17:54:29
Data access objects in MongoDB
In our EventDao interface, we are required to create a new Event object. With JPA, we can have our object ID automatically generated. With MongoDB, there are several ways to assign primary key identifiers, but for the sake of this demonstration, we are just going to use an atomic counter, as follows:
//src/main/java/com/packtpub/springsecurity/dataaccess/MongoEventDao.java
...
import java.util.concurrent.atomic.AtomicInteger;
@Repository
public class MongoEventDao implements EventDao {
// Simple Primary Key Generator
private AtomicInteger eventPK = new AtomicInteger(102);
...
@Override
public int createEvent(Event event) {
...
// Get the next PK instance
event.setId(eventPK.incrementAndGet());
Event newEvent = repository.save(event);
return newEvent.getId();
}
...
There was technically no change to our CalendarUserDao object, but for consistency in this book, we renamed the implementation file to denote the use of Mongo:
@Repository
public class MongoCalendarUserDao implements CalendarUserDao {
There are no other Data Access Objects (DAO) changes required for this refactoring example.
Go ahead and start the application, and it will behave just as before. Try to log in as user1 and admin1, and test it to ensure that both users can add new events to the system, to ensure the mapping is correct for the entire application.
You should be starting with the source from chapter05.05-calendar.