Thursday, February 2, 2023

Integrate MySQL and Hibernate in a Spring Boot application:

 

Here's a simple example of how you might integrate MySQL and Hibernate in a Spring Boot application:

  1. First, add the following dependencies to your pom.xml file:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
  1. Next, define your entity class and annotate it with JPA annotations:

import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String name; private int age; // getters and setters }
  1. Define a repository interface to interact with the MySQL database:

import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { User findByName(String name); }
  1. In your application configuration file (application.properties), configure the connection to MySQL:

spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=password spring.jpa.hibernate.ddl-auto=update
  1. Finally, in your main class, you can use the repository to perform CRUD operations on the User entity:

import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean CommandLineRunner init(UserRepository repository) { return args -> { repository.deleteAll(); repository.save(new User("John", 25)); repository.save(new User("Jane", 30)); repository.save(new User("Jim", 35)); System.out.println("Users found with findAll():"); System.out.println("-------------------------------"); for (User user : repository.findAll()) { System.out.println(user); } System.out.println(); System.out.println("User found with findByName('Jane'):"); System.out.println("--------------------------------");

No comments:

Post a Comment