Share with   

Manual Connect MySQL Database Server With Java Spring Boot Application

We are connecting MySQL database connection to spring boot web API application and create table auto using Entity Framework.


1) Configure Add Bellow Dependency In pom.xml file

Add My-SQL dependency.

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>

 

Add Lombok dependency if not available

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>provided</scope>
</dependency>

 

Add persistence dependency if not available for create entity table.

<dependency>
   <groupId>javax.persistence</groupId>
   <artifactId>persistence-api</artifactId>
   <scope>provided</scope>
</dependency>

 

Add spring boot jpa dependency if not available

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Above all dependencies are required to configure database connectivity and creating table by using entity table.

 

2) Add MySQL Credentials in spring properties file.

spring.datasource.url=jdbc:mysql://localhost:3306/test_api?allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.username='your database username'
spring.datasource.password='add database password'
#spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update

 

3) Create Model for create table. E.g. We are going to create Employee Table

Under main application package create model folder or package and in that create Employee,java file and in that write below code or you can change as per requirement in table columns.

package com.test_app.testapp.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;

@Data
@Entity
@Table(name = "employees")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "first_name",nullable = false)
    private String firstName;

    @Column(name = "last_name",nullable = false)
    private String lastName;

    @Column(name = "email",nullable = false)
    private String email;
    
}

Above model will create employees name table in your database with column having id, first_name, last_name, email. You can modifiy and change this as per your table requirement

 

4) Run Your Spring Application

Check in console everything is good and check hibernate will automatically create your table under your database. You can verify by opening your MySQL server.

 

5) Done.

 

Thank you for watching the article.

If you like, please like and share with your developer friends.

Author Image
Guest User

0 Comments