본문 바로가기

Spring/Lib

Spring Boot - JPA

반응형

Gradle

implementation 'mysql:mysql-connector-java:8.0.33'
implementation 'com.h2database:h2:2.2.220'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa:3.1.1'

Yml

spring
    datasource:
        url: jdbc:mysql://ServerAddress:Port/Dbname
        username: username
        password: password
        driver-class-name: com.mysql.cj.jdbc.Driver
      jpa:
        database-platform: org.hibernate.dialect.MySQL8Dialect
        hibernate:
          ddl-auto: none
          naming:
            physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
        properties:
          hibernate:
            show_sql: true
            format_sql: true
            use_sql_comments: true

Service

@Service
public class SigninService {

    private final SigninDao signinDao;

    @Autowired
    public SigninService(SigninDao signinDao) {
        this.signinDao = signinDao;
    }

    @Transactional
    public JSONObject Signin(JSONObject Parameter) {
        JSONObject Result = new JSONObject();
        try {

            String KeyList[] = { "Email", "Password" };
            for (String Key : KeyList) {
                // Parameter 체크
                if (!Parameter.containsKey(Key)) {
                    // 파라미터가 부족한 경우 에러 코드 1001
                    throw new ErrorException(ErrorCode.MISSING_PARAMETER);
                }
            }
            String Email = Parameter.optString("Email");
            String Password = Parameter.optString("Password");
            

            User user = signinDao.findByEmailAndPassword(Email, Password);

            if (user == null) {
                // 사용자가 없는 경우 에러 코드 1002
                throw new ErrorException(ErrorCode.INVALID_PARAMETER);
            } else {
                Result.put("Name",user.getName());
                Result.put("status", "200");
            }

        } catch (ErrorException e) {
            // 예외가 발생했을 때, 에러 코드와 에러 메시지를 Result JSON에 추가하여 반환합니다.
            Result.put("status", "error");
            Result.put("errorCode", e.getErrorCode().getCode());
            Result.put("errorMessage", e.getErrorCode().getMessage());
            System.out.println(Result.toString());
        }
        System.out.println(Result.toString());
        return Result;
    }
}

Dto

@Setter
@Getter
@Entity
@Table(name = "User")
public class User {

    @Id
    private String email;

    private String password;
    private String name;
}

Dao

public interface SigninDao extends JpaRepository<User, String> {
    User findByEmailAndPassword(String Email, String Password);
}

ErrorCode (에러처리)

public enum ErrorCode {
    MISSING_PARAMETER(1001, "Parameter is missing"),
    INVALID_PARAMETER(1002, "Invalid parameter"),
    //에러코드 지속적으로 추가
    ;

    private final int code;
    private final String message;

    ErrorCode(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

ErrorException (에러처리)

public class ErrorException extends RuntimeException {
    private final ErrorCode errorCode;

    public ErrorException(ErrorCode errorCode) {
        super(errorCode.getMessage());
        this.errorCode = errorCode;
    }

    public ErrorCode getErrorCode() {
        return errorCode;
    }
}

 

'Spring > Lib' 카테고리의 다른 글

Spring Boot-Jasypt  (0) 2023.08.08