A REST API that forgets everything when it restarts is not much use. The next step after your first Spring Boot endpoint is storing data in a real database. With Spring Data JPA, connecting to MySQL takes only a few files.
Step 1: dependencies
Add Spring Data JPA and the MySQL driver to your project (both are available in Spring Initializr). JPA is the standard; Hibernate is the library that implements it behind the scenes.
Step 2: connection settings
In application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/coursedb
spring.datasource.username=appuser
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=update
Read the password from an environment variable rather than writing it in the file. ddl-auto=update is convenient while learning; real projects use migration tools such as Flyway instead.
Step 3: an entity
@Entity
public class Course {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private int durationMonths;
// getters and setters
}
Step 4: a repository
public interface CourseRepository extends JpaRepository<Course, Long> {
List<Course> findByTitleContaining(String text);
}
You write no SQL for basic operations. save(), findById(), findAll() and deleteById() come free, and Spring builds queries from method names like findByTitleContaining.
Step 5: use it from a service
Inject the repository into a service class with constructor injection, and call the service from your controller. Keeping database logic out of controllers makes the code easier to test.
Common errors
- Communications link failure: MySQL is not running, or the host or port is wrong.
- Access denied: wrong username or password, or the user has no rights on the database.
- Table not found: the entity name does not match the table, or
ddl-autois off.
Background: Spring Boot: your first REST API, Hibernate and JPA explained and MySQL basics for Java developers.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
