Configure Spring Boot With MySQL Database

Home / Configure Spring Boot With MySQL Database

Configure your application with database is the basic need of every project. Spring Boot provides JPA (java Persistance API) to Connect to MySQL database. For connecting our Spring Boot application we have to follow some basic steps, and steps are:

  1. Create a Spring Boot Project with MySQL and JPA dependency
  2. Configure MySql properties in application.properties file
  3. create a Model Class
  4. Create a interface repository that extends JpaRepository interface
  5. Create a Controller Class
  6. Create a Service Class for business logic.
  7. Create a Response Class For Display Custom Responses.

2- Configure MySql properties in application.properties file

 spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/vasu
spring.datasource.username=root
spring.datasource.password=12345@
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
hibernate.hbm2ddl.auto=create-drop
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardI mpl

3- Create a Model Class, We are creating a Model Class With Name Student

 @Entity
@Table(name = "Student")
public class StudentModel implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Id", nullable = false)
private Long id;

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

@Column(name = "Age", nullable = false)
private int age;

@Column(name = "Email", nullable = false, unique = true)
private String email;

//Constructor
//Getter-Setter

4- Create a interface repository that extends JpaRepository interface

 @Repository
public interface StudentRepositry extends JpaRepository {
}

5- Create a Controller Class

 @RestController
public class StudentController {

@Autowired
private StudentService service;

@GetMapping("/")
public ResponseEntity getAll() {
ResponseEntity get = service.get();
return get;
}

@GetMapping("/getById/{id}")
public ResponseEntity getById(@PathVariable("id") Long Id) {
ResponseEntity byId = service.getById(Id);
return byId;
}

@PostMapping("/update")
public ResponseEntity update(@RequestParam Long id,
@RequestParam String name,
@RequestParam String email,
@RequestParam int age) {
ResponseEntity update = service.update(id, new StudentModel(name, age, email));
return update;
}

@GetMapping("/delete/{id}")
public ResponseEntity delete(@PathVariable("id") Long id) {
ResponseEntity delete = service.delete(id);
return delete;
}

@PostMapping("/insert")
public ResponseEntity insert(@RequestParam String name,
@RequestParam String email,
@RequestParam int age) {

ResponseEntity save = service.save(new StudentModel(name, age, email));
return save;
}

6- Create a Service Class for business logic

@Service
public class StudentService {
private static final Logger logger = LoggerFactory.getLogger(StudentService.class.getName());

@Autowired
private StudentRepositry dao;
@Autowired
private Responses response;

public ResponseEntity save(StudentModel student) {
try {
StudentModel save = dao.save(student);
return new ResponseEntity(save, HttpStatus.OK);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}


public ResponseEntity get() {
try {
List findAll = dao.findAll();
return new ResponseEntity(findAll, HttpStatus.OK);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

public ResponseEntity update(Long id, StudentModel student) {
try {
Optional findById = dao.findById(id);
if (findById.isPresent()) {
StudentModel get = findById.get();
get.setAge(student.getAge());
get.setEmail(student.getEmail());
get.setName(student.getName());
StudentModel save = dao.save(get);
return new ResponseEntity(save, HttpStatus.OK);
}
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}


public ResponseEntity delete(Long id) {
try {
dao.deleteById(id);
return new ResponseEntity(response.getResponse(response.OK), HttpStatus.OK);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}


public ResponseEntity getById(Long id) {
try {
Optional findById = dao.findById(id);
if (findById.isPresent()) {
StudentModel get = findById.get();
return new ResponseEntity<Object>(get, HttpStatus.OK); }
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
logger.error("ERROR", e);
return new ResponseEntity(response.getResponse(response.ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

7- Create a Response Class For Display Custom Responses.

/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/

@Component
public class Responses {
private static final Logger logger = LoggerFactory.getLogger(Responses.class.getName());

public static final int OK = 0;
public static final int ERROR = 1;
public static final int INSUFFICIENT_DATA = 3;
public static final int INVALID_USER = 4;
public static final int UNKNOWN = 501;

public static JSONObject getResponse(int code) {
logger.info("vvv:: responseCode= " + code);
JSONObject response = new JSONObject();
switch (code) {
case OK:
response.put("code", OK);
response.put("message", "OK");
break;
case ERROR:
response.put("code", ERROR);
response.put("message", "Internal Error");
break;
case INSUFFICIENT_DATA:
response.put("code", INSUFFICIENT_DATA);
response.put("message", "Insufficient Data");
break;
case INVALID_USER:
response.put("code", INVALID_USER);
response.put("message", "Invalid User");
break;
default:
response.put("code", UNKNOWN);
response.put("message", "Unknown Response code");
}
logger.info("vvv:: MakeResponse= " + response); return response;
}
}

OUTPUT

Help Others, Please Share

About Author

1 Comment
  1. Short Hairstyles

    Just wish to say your article is as amazing. The clarity to your submit is just cool and i can assume you are an expert on this subject. Fine together with your permission let me to grab your RSS feed to stay up to date with impending post. Thank you one million and please continue the gratifying work.

Leave a Reply

Your email address will not be published. Required fields are marked *