Setup Spring Boot with JPA and MySQL

robyconte

Roberto Conte Rosito

Posted on March 21, 2023

Setup Spring Boot with JPA and MySQL

Welcome back to my dev notes!

Few things that I’ve to remember next time I need to setup a Spring Boot project with JPA and MySQL:

  • Add the following dependencies to your pom.xml:
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
</dependency>

Enter fullscreen mode Exit fullscreen mode
  • Add the following properties to your application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Enter fullscreen mode Exit fullscreen mode
  • Create your model using @Entity and @Id annotations:
@Entity
public class User {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;
 private String name;
 private String email;
 private String password;
 // getters and setters
}

Enter fullscreen mode Exit fullscreen mode
  • Create your repository extending JpaRepository adding @Repository annotation:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {}

Enter fullscreen mode Exit fullscreen mode

Now you are ready to @Autowired your repository and use it in your services/controllers.

That’s all for today, see you next time!

💖 💪 🙅 🚩
robyconte
Roberto Conte Rosito

Posted on March 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related