Spring Boot with JPA and MySQL
Welcome back to my dev notes!
Here are a few things I want to remember the next time I set up a Spring Boot project with JPA and MySQL:
- Add the following dependencies to your
pom.xml:
1<dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-data-jpa</artifactId>
4</dependency>
5<dependency>
6 <groupId>mysql</groupId>
7 <artifactId>mysql-connector-java</artifactId>
8</dependency>
- Add the following properties to your
application.properties:
1spring.datasource.url=jdbc:mysql://localhost:3306/db_name
2spring.datasource.username=root
3spring.datasource.password=root
4spring.jpa.hibernate.ddl-auto=update
5spring.jpa.show-sql=true
- Create your model using the
@Entityand@Idannotations:
1@Entity
2public class User {
3 @Id
4 @GeneratedValue(strategy = GenerationType.IDENTITY)
5 private Long id;
6 private String name;
7 private String email;
8 private String password;
9 // getters and setters
10}
- Create your repository by extending
JpaRepositoryand adding the@Repositoryannotation:
1@Repository
2public interface UserRepository
3 extends JpaRepository<User, Long> {}
Now you are ready to @Autowired your repository and use it in your services or controllers.
That’s all for today. See you next time!
comments powered by Disqus