From MySQL to MongoDB in Spring Boot — Everything That Changed in My Code
In my last post I wrote about an error that cost me a full evening: my pom.xml had the MongoDB starter, but my code was still full of JPA annotations. The compiler kept saying cannot find symbol: class Entity . That post was about the error. This post is about the fix — every single line I had to change to move my Task Manager project from MySQL to MongoDB. If you are planning the same switch,…
In my last post, I detailed an issue that caused me a full evening of frustration. The problem was that my pom.xml contained the MongoDB starter, but my code was still littered with JPA annotations. The compiler complained about "cannot find symbol: class Entity." This post will focus on the solution to switch my Task Manager project from MySQL to MongoDB, providing a comprehensive checklist I wish I had before.
First, the dependency changes were straightforward. The old setup used spring-boot-starter-data-jpa and mysql-connector-j as dependencies, while the new setup only requires spring-boot-starter-data-mongodb. By removing the JPA starter, I avoided mixing two distinct worlds of databases, which eventually led to runtime issues.
Next, I streamlined the application.properties file. Instead of specifying the MySQL URL, username, and password, I replaced it with a single line for MongoDB's URI. This reduction simplified the configuration, as MongoDB does not require a schema or dialect, and the database and collections are automatically created upon inserting documents.
The most significant changes occurred in the model class. I had to modify the Task class to adapt to MongoDB's structure. The key differences were:
1. The @Document annotation replaced @Entity and specified the collection name.
2. The @Id annotation changed from jakarta.persistence to org.springframework.data.annotation and generated a String ID instead of a Long.
3. The @ManyToOne and @JoinColumn annotations transformed into @DBRef.
4. The @GeneratedValue annotation was entirely removed, as MongoDB generates an ObjectId.
This transformation required careful attention to imports, as both JPA and MongoDB use the same annotation name for their document ID. Importing the wrong one could lead to documents being saved with incorrect IDs, causing issues with data retrieval later on.
Lastly, the repository class needed modifications. The previous implementation using JPA's entity management had to be adapted to work with the new MongoDB repository implementation. By following these steps, I successfully migrated my Task Manager project from MySQL to MongoDB, avoiding runtime errors caused by mixing two different database systems.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.