Skip to content

Latest commit

 

History

History
378 lines (315 loc) · 10.3 KB

File metadata and controls

378 lines (315 loc) · 10.3 KB

SprinMySQLJpa

  1. Create a Spring boot gradle project: start.spring.io

Demo Screenshot 1

- Add dependencies: Web, JPA, MySQL
- After import project in IntelliJ IDEA, create project structure by packaging to manage projects files. It's optional
package names:
config - Configuration: In this diractory contain java main class files, as like main function class here.
ctrl - Control: In this directory contain controlar java files. Control concept comes from MVC architecture in Spring.
model - Model: In this directory contain all model java files. Model concept from MVC architecture in Spring.
repo - Repository: In this directory contain all repository java interface files. Repository act like DAO (Data Access Object) concept
service - Service: In this directory contain all repo accessable java class and java interface files. Service act as middle position between controller and repository
...

Demo Screenshot 1



- set packages as component and entityScan by annotation in main class


--- SpringMySQLJpaApplication---
package com.emran.MySQLDemo.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;


@SpringBootApplication
@ComponentScan("com.emran.MySQLDemo")
@EntityScan("com.emran.MySQLDemo.model")
@EnableJpaRepositories(basePackages = {"com.emran.MySQLDemo.repo"})
//add extends SpringBootServletInitializer this for war
public class SpringMySQLJpaApplication {

public static void main(String[] args) {
	SpringApplication.run(SpringMySQLJpaApplication.class, args);

}

}
-------------------------------


- Now create model with table colomun and other annotation in model package.
--- BaseModel.java ---
package com.emran.MySQLDemo.model;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;

@MappedSuperclass
public class BaseModel implements Serializable {

@Id
@Column(name="ID", unique = true)
private Integer id;

//Default constructor
public BaseModel(){

}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

@Override
public String toString() {
    return id.toString();
}

}
-------------------------------


Add a enum file for gender
--- GenderEnm.java ---

package com.emran.MySQLDemo.model;

public enum GenderEnm {
MALE, FEMALE, OTHER
}
-------------------------------


--- Human.java ---

package com.emran.MySQLDemo.model;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;

@MappedSuperclass
public class Human extends BaseModel {

@Column(name = "FIRST_NAME", nullable = false, length = 30)
private String firstName;

@Column(name = "LAST_NAME", nullable = true, length = 15)
private String lastName;

@Column(name = "DOB")
@Temporal(TemporalType.DATE)
private Date dob;

@Column(name = "GENDER", nullable = false, length = 15)
private GenderEnm gender;


public Human() {

}

public Human(String firstName, String lastName, Date dob, GenderEnm gender) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.dob = dob;
    this.gender = gender;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public void setDob(Date dob) {
    this.dob = dob;
}

public void setGender(GenderEnm gender) {
    this.gender = gender;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public Date getDob() {
    return dob;
}

public GenderEnm getGender() {
    return gender;
}

@Override
public String toString() {
    return "Human{" +
            "firstName='" + firstName + '\'' +
            ", lastName='" + lastName + '\'' +
            ", dob=" + dob +
            ", gender=" + gender +
            '}'+super.toString();
}

}
-------------------------------


--- User.java ---

package com.emran.MySQLDemo.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;

@Entity
@Table(name = "USER")
public class User extends Human{

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

@Column(name = "PHONE", nullable = true, length = 30)
private String phone;

public User() { }


public User(String email, String phone) {
    this.email = email;
    this.phone = phone;
}

public User(String firstName, String lastName, Date dob, GenderEnm gender, String email, String phone) {
    super(firstName, lastName, dob, gender);
    this.email = email;
    this.phone = phone;
}

public void setEmail(String email) {
    this.email = email;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String getEmail() {
    return email;
}

public String getPhone() {
    return phone;
}

@Override
public String toString() {
    return "User{" +
            "email='" + email + '\'' +
            ", phone='" + phone + '\'' +
            '}'+""+super.toString();
}

}
-------------------------------


Create repository for user


--- UserRepo ---

package com.emran.MySQLDemo.repo;

import com.emran.MySQLDemo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface UserRepo extends JpaRepository<User,Integer> {

User findByEmail(String email);

List<User> findAll();

}
-------------------------------


Create user service interface and user service implementation


--- UserService ---

package com.emran.MySQLDemo.service;

import com.emran.MySQLDemo.model.User;

import java.util.List;

public interface UserService {

List<User> findAll();

User findUserByEmail(String email);

}
-------------------------------


--- UserServiceImpl ---

package com.emran.MySQLDemo.service;

import com.emran.MySQLDemo.model.User;
import com.emran.MySQLDemo.repo.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{

@Autowired
UserRepo userRepo;

@Override
public List<User> findAll() {
    return userRepo.findAll();
}

@Override
public User findUserByEmail(String email) {
    return userRepo.findByEmail(email);
}

}


-------------------------------


Create controllare for user model, user controllare use for user table and user service.


--- UserCtrl ---
package com.emran.MySQLDemo.ctrl;
import com.emran.MySQLDemo.model.User;
import com.emran.MySQLDemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserCtrl {

@Autowired
UserService userService;

@GetMapping(value = "/user")
public String userAll(){

    List<User> users = userService.findAll();

    return ""+users;
}

@GetMapping(value = "/user/{email}")
public String userByEmail(@PathVariable String email){

    User user = userService.findUserByEmail(email);

    return ""+user;
}

}
-------------------------------

now configure

application.yml

file

Demo Screenshot 1



server:
port: 9090
servlet:
context-path: /demo

spring:
jpa:
generate-ddl: true
show-sql: true
hibernate:
show-sql: true
ddl-auto: update
naming.physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
properties:
hibernate:
default_schema: app
id.new_generator_mappings: true
dialect: org.hibernate.dialect.MySQL5Dialect
datasource:
url: jdbc:mysql://localhost:3306/bd_spring_demo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password:

- In UserCtrl.java file


Use userAll() function by url: localhost:9090/demo/user
to get all user data
and
Use userByEmail() function by url: localhost:9090/demo/user/name@mail.com
to get single user information by email
database name: bd_spring_demo

- Noe run this project and browse
localhost:9090/demo/user
and
localhost:9090/demo/user/name@mail.com

Related tutorial:

----------------------
Spring Boot MySQL database connect by JPA with hibernate
https://youtu.be/ogbM5F0dKXk