본문 바로가기
Projects/센서 모니터링 시스템

[센서 모니터링 시스템] 6. Spring 서버 기본환경 설정

by DevJaewoo 2022. 8. 17.
반응형

Intro

디바이스 코드는 어느정도 됐으니 이제 Request를 수신할 서버를 만들어야 한다.

지금 당장은 센서 데이터 CREATE / READ 까지만 가능하도록 만들 예정이다.

 

프로젝트를 시작하기 전 PostgreSQL을 사용하기 위해 아래의 사이트에서 설치하자.

https://www.enterprisedb.com/downloads/postgres-postgresql-downloads

 

Download PostgreSQL

PostgreSQL Database Download

www.enterprisedb.com


프로젝트 생성

우선 아래의 Dependencies들을 추가하여 프로젝트를 생성했다.

  • Spring Web
  • Spring Data JPA
  • Spring Validation
  • Lombok
  • Spring Boot Devtools
  • PostgreSQL
  • QueryDSL

Gradle 코드는 다음과 같다.

plugins {
    id 'org.springframework.boot' version '2.7.2'
    id 'io.spring.dependency-management' version '1.0.12.RELEASE'

    //querydsl
    id "com.ewerk.gradle.plugins.querydsl" version "1.0.10"

    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.h2database:h2'
    runtimeOnly 'org.postgresql:postgresql'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

    //querydsl
    implementation "com.querydsl:querydsl-jpa:5.0.0"
    annotationProcessor "com.querydsl:querydsl-apt:5.0.0"
}

tasks.named('test') {
    useJUnitPlatform()
}

// + querydsl
def querydslDir = "$buildDir/generated/querydsl"
querydsl {
    jpa = true
    querydslSourcesDir = querydslDir
}
sourceSets {
    main.java.srcDir querydslDir
}
configurations {
    querydsl.extendsFrom compileClasspath
}
compileQuerydsl {
    options.annotationProcessorPath = configurations.querydsl
}
// - querydsl

 

그 다음 JPA가 PostrgeSQL DB에 연결하기 위해 application.yml 파일을 설정해줬다.

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/postgres
    driver-class-name: org.postgresql.Driver
    username: postgres
    password: postgres

  jpa:
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        show_sql: true
        format_sql: true

 

설정이 완료되면 실행시켜 서버가 잘 켜지는지 확인하자.

만약 잘못됐다면 서버가 에러를 띄우며 뻗어버릴것이다.

실행 성공
실행이 잘 된다.


엔티티 생성

이제 DB에 넣을 엔티티를 생성해야 한다.

프로젝트가 워낙 간단하기 때문에 만들어야 할 엔티티가 Client, Sensor 2개밖에 없다.

 

Client.java

package com.example.sensormonitoringserver.entity;

import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
@Getter
@NoArgsConstructor
public class Client {

    @Id @GeneratedValue
    @Column(name = "client_id")
    private Long id;

    private String name;

    public Client(String name) {
        this.name = name;
    }
}

 

Sensor.java

package com.example.sensormonitoringserver.entity;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Getter
@Setter
@NoArgsConstructor
public class Sensor {

    @Id @GeneratedValue
    @Column(name = "sensor_id")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "client_id")
    private Client client;

    private double temp;
    private int eco2;
    private int tvoc;

    @Embedded
    private Coord accel = new Coord();

    private LocalDateTime createdDate;

    @PrePersist
    private void prePersist() {
        createdDate = LocalDateTime.now();
    }

    public Sensor(Client client, double temp, int eco2, int tvoc, Coord accel) {
        this.client = client;
        this.temp = temp;
        this.eco2 = eco2;
        this.tvoc = tvoc;
        if(accel != null) this.accel = accel;
    }
}

 

Coord.java

package com.example.sensormonitoringserver.entity;

import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.persistence.Embeddable;

@Embeddable
@Getter
@NoArgsConstructor
public class Coord {
    private double x;
    private double y;
    private double z;

    public Coord(double x, double y, double z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}

 

서버를 다시 실행시켜 테이블이 잘 생성되는지 확인하자.

콘솔 창에 뜨는 메시지를 통해 확인해도 되고, DB에서 desc 명령어를 쳐서 확인해도 된다.

난 Intellij에서 제공하는 Datasource 기능을 통해 확인했다.

Coord는 Embeddable이기 때문에 테이블이 생성되지 않는다.

 

 

반응형