How do you connect Spring Boot to a database?
To connect Spring Boot to a database, follow these steps:
- Add Dependencies:
- For JPA (e.g., MySQL, PostgreSQL), add the
spring-boot-starter-data-jpa
dependency. - For Database driver (e.g., MySQL, H2), add the corresponding database driver dependency (e.g.,
mysql-connector-java
).
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
- For JPA (e.g., MySQL, PostgreSQL), add the
- Configure Database Connection:
- In
application.properties
orapplication.yml
, set the database connection details (URL, username, password, dialect).
spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=update spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
- In
- Create Entity Classes:
- Define your model classes with
@Entity
and map them to your database tables.
@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // getters and setters }
- Define your model classes with
- Create Repository:
- Use Spring Data JPA’s
JpaRepository
to perform CRUD operations.
public interface UserRepository extends JpaRepository<User, Long> { }
- Use Spring Data JPA’s
- Service Layer:
- In the service layer, inject the repository and use it to interact with the database.
@Service public class UserService { @Autowired private UserRepository userRepository; public List<User> getAllUsers() { return userRepository.findAll(); } }
In summary, Spring Boot simplifies database integration by automatically configuring a connection and providing tools like JPA to easily interact with the database using simple annotations.