티스토리 뷰

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
plugins {
    id 'org.springframework.boot' version '2.2.5.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
    id 'war'
    id 'com.ewerk.gradle.plugins.querydsl' version '1.0.10'
}
 
group = 'com.chatbot..'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
 
repositories {
    mavenCentral()
}
 
dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter', version: '2.2.5.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.2.5.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web-services', version: '2.2.5.RELEASE'
    providedCompile group: 'org.projectlombok', name: 'lombok', version: '1.18.12'
    compile group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '2.5.4'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.2.5.RELEASE'
    compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
    compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
    compile group: 'com.querydsl', name: 'querydsl-jpa', version: '4.3.0'
    compile group: 'com.querydsl', name: 'querydsl-apt', version: '4.3.0'
    compile group: 'com.amazonaws', name: 'aws-java-sdk', version: '1.11.744'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}
 
test {
    useJUnitPlatform()
}
def querydslSrcDir = 'src/main/generated'
 
querydsl{
    library = 'com.querydsl:querydsl-apt'
    jpa = true
    querydslSourcesDir = querydslSrcDir
}
 
compileQuerydsl{
    options.annotationProcessorPath = configurations.querydsl
}
configurations {
    querydsl.extendsFrom compileClasspath
}
sourceSets{
    main{
        java{
            srcDirs = ['src/main/java', querydslSrcDir]
        }
    }
}
cs

 

 

1
2
3
4
5
6
7
8
9
10
mysql -u root -p
root
create database mobeom;
show databases;
use mobeom
create user 'mobeom'@'localhost' identified by 'mobeom';
grant all privileges on mobeom.* to mobeom@localhost;
flush privileges;
exit;
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
CREATE TABLE board
(
    `board_id`    INT           NOT NULL    AUTO_INCREMENT,
    `board_name`  VARCHAR(5)    NOT NULL,
    PRIMARY KEY (board_id)
)default character set utf8 collate UTF8_GENERAL_CI;
 
CREATE TABLE post
(
    `post_id`       INT              NOT NULL    AUTO_INCREMENT,
    `board_id`      INT              NOT NULL,
    `reg_date`      DATETIME         NOT NULL,
    `category`      VARCHAR(10)      NOT NULL,
    `post_title`    VARCHAR(30)      NOT NULL,
    `contents`      VARCHAR(1000)    NOT NULL,
    `read_count`    INT              NOT NULL,
    `modi_date`     DATETIME         NOT NULL,
    `notice_yn`     BOOLEAN          NOT NULL,
    `delete_yn`     BOOLEAN          NOT NULL,
    `star_rating`   INT              NOT NULL,
    `comment`       VARCHAR(500)     NOT NULL,
    `recommend_id`  INT              NOT NULL,
    `user_id`       INT              NOT NULL,
    PRIMARY KEY (post_id)
)default character set utf8 collate UTF8_GENERAL_CI;
 
CREATE TABLE image
(
    `image_id`     INT             NOT NULL    AUTO_INCREMENT,
    `image_url`    VARCHAR(300)    NOT NULL,
    `update_date`  DATETIME        NOT NULL,
    `image_cate`   VARCHAR(10)     NOT NULL,
    `post_id`      INT             NOT NULL,
    `board_id`     INT             NOT NULL,
    PRIMARY KEY (image_id)
)default character set utf8 collate UTF8_GENERAL_CI;
 
CREATE TABLE recommend
(
    `recommend_type` INT NOT NULL,
    `recommend_tag`  VARCHAR(50NULL,
    PRIMARY KEY (recommend_type)
)default character set utf8 collate UTF8_GENERAL_CI;
 
CREATE TABLE sales
(
    `sales_id`      INT NOT NULL AUTO_INCREMENT,
    `sales_date`    DATETIME    NOT NULL,
    `unit_price`    INT NOT NULL,
    `use_date`      DATETIME    NOT NULL,
    `gift_yn`       INT NOT NULL,
    `cancel_date`   DATETIME    NOT NULL,
    `currency_state`    INT NOT NULL,
    `payment_code`  INT NOT NULL,
    `payment_type_code` INT NOT NULL,
    `payment_name`  VARCHAR(30NOT NULL,
    PRIMARY KEY (sales_id)
)default character set utf8 collate UTF8_GENERAL_CI;
 
CREATE TABLE `store` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `store_name` VARCHAR(200),
    `store_type_code` INT,
    `store_type` VARCHAR(50),
    `local_name` VARCHAR(10),
    `road_address` VARCHAR(200),
    `store_phone` VARCHAR(15),
    `latitude` FLOAT,
    `logitude` FLOAT,
    `star_ranking` INT,
    `search_result_count` INT,
    PRIMARY KEY (`id`)
)default character set utf8 collate UTF8_GENERAL_CI;
 
CREATE TABLE subsidyPolicy
(
    `subsidy_policy_id` INT NOT NULL AUTO_INCREMENT,
    `condition_age` INT NULL,
    `condition_income`  INT NULL,
    `condition_dependents` INT NULL,
    PRIMARY KEY (subsidy_policy_id)
)default character set utf8 collate UTF8_GENERAL_CI;
 
CREATE TABLE `user`(
    `id` INT(11NOT NULL AUTO_INCREMENT,
    `user_id` VARCHAR(30NULL DEFAULT NULL COLLATE 'utf8_general_ci',
    `password` VARCHAR(80NULL DEFAULT NULL COLLATE 'utf8_general_ci',
    `name` VARCHAR(10NULL DEFAULT NULL COLLATE 'utf8_general_ci',
    `birth_date` DATE NULL DEFAULT NULL,
    `gender` VARCHAR(2NULL DEFAULT NULL COLLATE 'utf8_general_ci',
    `email` VARCHAR(100NULL DEFAULT NULL COLLATE 'utf8_general_ci',
    `join_date` DATE NULL DEFAULT NULL,
    `withdraw_date` DATE NULL DEFAULT '0000-00-00',
    `admin_key` INT(11NULL DEFAULT NULL,
    `card_number` VARCHAR(50NULL DEFAULT NULL COLLATE 'utf8_general_ci',
    `default_addr` VARCHAR(100NULL DEFAULT NULL COLLATE 'utf8_general_ci',
    `optional_addr` VARCHAR(100NULL DEFAULT NULL COLLATE 'utf8_general_ci',
    PRIMARY KEY (`id`)
)default character set utf8 collate UTF8_GENERAL_CI;
 
 
cs
1
2
3
4
5
6
CREATE TABLE local_currency
(
    `local_currency_id`  INT            NOT NULL    AUTO_INCREMENT,
    `use_local`          VARCHAR(10)    NULL,
    PRIMARY KEY (local_currency_id)
)default character set utf8 collate UTF8_GENERAL_CI;
cs

인텔리제이 기준 설정입니다.

 

 

 

 

DB 연결이 끝났습니다. 그래들을 클릭합니다.

 

Entity 파일을 오픈합니다.

 

1
2
3
4
5
6
7
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Entity;
import javax.persistence.Table;
 
@Entity @Getter @Setter @ToString @Table(name="article")
cs

 

아래와 같이 에러표시가 나는 경우가 있습니다.

 

에러표시난 부분을 우클릭하면 아래와 같은 화면이 보입니다. 마리아디비와 연동시킵니다.

 

아래와 같이 compileQuerydsl 을 클릭합니다.

컴파일이 종료되면 콘솔에 다음과 같이 출력됩니다.

QBoard 와 같은 객체엔티티 파일이 생성됩니다.

 

우측상단에 Run Configurations 를 다시 Spring Boot 로 바꿔줍니다.

 

 

 

 

 

실행하면 인텔리제이에서 아래와 같은 에러가 발생합니다.

 

 

<property name="dynamic.classpath" value="true" /> 를 카피해서 60번째 라인에 넣습니다.

 

application.yml 에서 테이블이 이미 완성된 상태에서 9 ~ 11 번 라인은 충돌이 납니다. 삭제합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
spring:
  mvc:
    view:
      suffix: .html
 
  jpa:
    show-sql: true
    database: mysql
    hibernate:
      ddl-auto: update
    generate-ddl: true
 
  datasource:
    driver-class-name: org.mariadb.jdbc.Driver
    url: jdbc:mariadb://127.0.0.1:3306/mobeom
    username: mobeom
    password: mobeom
 
cs

 

 

실행합니다.

 

 

화면은 리액트 별도의 프로젝트를 했으므로 위와 같이 나오는 것이 정상입니다.

이제 JSON 파일을 출력하겠습니다.

 

 

dummy 패키지에 DummyController 파일을 아래와 같이 작성합니다. 임시 사용자 정보를 DB에 저장하려고 합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package com.mobeom.local_currency.dummy;
 
import com.mobeom.local_currency.user.User;
import com.mobeom.local_currency.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
 
import static java.lang.Integer.parseInt;
 
@RestController
@RequestMapping("/dummy")
public class DummyController {
    @Autowired
    UserRepository userRepository;
 
    @PostMapping("/user-generator")
    public ResponseEntity<List<User>> createRandomUser() {
        IDummyGenerator dummyGenerator = () -> {
            List<User> userList = new ArrayList<>();
            for(int i = 0; i < 10000; i++) {
                User user = new User();
                user.setUserId(RandomUserGenerator.generateRandomId()+RandomUserGenerator.generateRandomNo2());
                user.setPassword(RandomUserGenerator.generateRandomPw()+RandomUserGenerator.generateRandomPwNum());
                user.setName(RandomUserGenerator.generateRandomName());
                user.setBirthDate(RandomUserGenerator.generateRandomBirthDate());
                user.setGender(RandomUserGenerator.generateRandomGender());
                user.setEmail(RandomUserGenerator.generateRandomEmailId()+"@"+RandomUserGenerator.generateRandomEmail()+
                        RandomUserGenerator.generateRandomEmailEnd());
                user.setJoinDate(RandomUserGenerator.generateRandomJoinDate());
                user.setAdminKey(0);
                user.setDefaultAddr(RandomUserGenerator.generateRandomAddress());
                userList.add(user);
            }
            return userRepository.saveAll(userList);
        };
 
        return ResponseEntity.ok(dummyGenerator.createRandomUser());
    }
}
@FunctionalInterface
interface IDummyGenerator {
    List<User> createRandomUser();
}
class RandomUserGenerator {
    // 아이디
    public static String generateRandomId() {
        String randomId = "";
        String ran = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        for(int i = 0; i < 6; i++) {
            randomId += ran.charAt((int)(Math.random() * ran.length()));
        }
        return randomId;
    }
    public static String generateRandomNo2() {
        return (int)(Math.random() * 99)+1 +"";
    }
 
    // 비밀번호
    public static String generateRandomPw() {
        String randomPw = "";
        String ran = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*";
        for(int i = 0; i < 12; i++) {
            randomPw += ran.charAt((int)(Math.random() * ran.length()));
        }
        return randomPw;
    }
    public static String generateRandomPwNum() {
        return (int)(Math.random() * 99)+1 +"";
    }
 
    // 랜덤 이름
    public static String generateRandomName() {
        List<String> lastName = Arrays.asList("김""이""박""최""정""강""조""윤""장""임""한""오""서""신",
                "권""황""안""송""류""전""홍""고""문""양""손""배""조""백""허""유""남""심",
                "노""정""하""곽""성""차""주""우""구""신""임""나""전""민""유""진""지""엄",
                "채""원""천""방""공""강""현""함""변""염""양""변""여""추""노""도""소""신",
                "석""선""설""마""길""주""연""방""위""표""명""기""반""왕""금""옥""육""인",
                "맹""제""모""장""남""탁""국""여""진""어""은""편""구""용");
        List<String> firstName = Arrays.asList("가""강""건""경""고""관""광""구""규""근""기""길""나",
                "남""노""누""다""단""달""담""대""덕""도""동""두""라""래""로""루""리""마",
                "만""명""무""문""미""민""바""박""백""범""별""병""보""빛""사""산""상""새",
                "서""석""선""설""섭""성""세""소""솔""수""숙""순""숭""슬""승""시""신""아",
                "안""애""엄""여""연""영""예""오""옥""완""요""용""우""원""월""위""유""윤",
                "율""으""은""의""이""익""인""일""잎""자""잔""장""재""전""정""제""조""종",
                "주""준""중""지""진""찬""창""채""천""철""초""춘""충""치""탐""태""택""판",
                "하""한""해""혁""현""형""혜""호""홍""화""환""회""효""훈""휘""희""운""모",
                "배""부""림""봉""혼""황""량""린""을""비""솜""공""면""탁""온""디""항""후",
                "려""균""묵""송""욱""휴""언""령""섬""들""견""추""걸""삼""열""웅""분""변",
                "양""출""타""흥""겸""곤""번""식""란""더""손""술""훔""반""빈""실""직""흠",
                "흔""악""람""뜸""권""복""심""헌""엽""학""개""롱""평""늘""늬""랑""얀""향",
                "울""련");
        Collections.shuffle(lastName);
        Collections.shuffle(firstName);
        return lastName.get(0+ firstName.get(0+ firstName.get(1);
    }
 
    //생년월일
    public static List<String> yearEnd =
            Arrays.asList("00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18");
    public static List<String> yearstart =
            Arrays.asList("19","20");
    public static List<String> month =
            Arrays.asList("01","02","03","04","05","06","07","08","09","10","11","12");
    public static List<String> date =
            Arrays.asList("01","02","03","04","05","06","07","08","09","10","11","12",
                    "13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31");
 
    public static LocalDate generateRandomBirthDate() {
        Collections.shuffle(yearstart);
        Collections.shuffle(month);
        Collections.shuffle(date);
        String yearDigit = yearstart.get(0);
        String dayDigit = date.get(0);
        String monthDigit = month.get(0);
        if(yearDigit.equals("19")) {
            String yearEnd = ((int)(Math.random() * 69+ 30+ "";
            yearDigit += yearEnd;
        } else if(yearDigit.equals("20")) {
            Collections.shuffle(yearEnd);
            yearDigit += yearEnd.get(0);
        }
        if(parseInt(monthDigit) == 4 || parseInt(monthDigit) == 6 ||
                parseInt(monthDigit) == 9 || parseInt(monthDigit) == 11 && parseInt(dayDigit) > 30) {
            dayDigit = "30";
        }
        if(parseInt(monthDigit) == 2 && parseInt(dayDigit) > 29) {
            dayDigit = "29";
        }
        if(parseInt(yearDigit) % 4 != 0 || parseInt(yearDigit) % 400 != 0 && parseInt(yearDigit) % 100 == 0) {
            if(parseInt(monthDigit) == 2 && parseInt(dayDigit) == 29) {
                dayDigit = "28";
            }
        }
        LocalDate randomBirthDate = LocalDate.of(parseInt(yearDigit),parseInt(monthDigit),parseInt(dayDigit));
        return randomBirthDate;
    }
 
    //성별
    public static String generateRandomGender() {
        String[] genderList = { "F""M" };
        int index = ((int)(Math.random()*10)+1);
        return genderList[(index%2)];
    }
 
    // 이메일
    public static String generateRandomEmailId() {
        String randomEmailId = "";
        String ran = "abcdefghijklmnopqrstuvwxyz1234567890";
        for(int i = 0; i < 6; i++) {
            randomEmailId += ran.charAt((int)(Math.random() * ran.length()));
        }
        return randomEmailId;
    }
    public static String generateRandomEmail() {
        String randomEmail = "";
        String ran = "abcdefghijklmnopqrstuvwxyz";
        for(int i = 0; i < 6; i++) {
            randomEmail += ran.charAt((int)(Math.random() * ran.length()));
        }
        return randomEmail;
    }
 
    public static String generateRandomEmailEnd() {
        String randomEmailEnd = "";
        String[] ran = {".kr",".com",".ac.kr",".co.kr",".net"};
        int ranIndex = (int)(Math.random() * ran.length);
        randomEmailEnd += ran[ranIndex];
        return randomEmailEnd;
    }
 
    // 가입일
    public static List<String> validMonth =
            Arrays.asList("01","02","03","04","05","06","07","08");
 
    public static LocalDate generateRandomJoinDate() {
 
        Collections.shuffle(validMonth);
        Collections.shuffle(date);
        String monthDigit = validMonth.get(0);
        String dayDigit = date.get(0);
        if(parseInt(monthDigit) == 4 || parseInt(monthDigit) == 6 && parseInt(dayDigit) > 30) {
            dayDigit = "30";
        }
        if(parseInt(monthDigit) == 2 && parseInt(dayDigit) > 29) {
            dayDigit = "29";
        }
        LocalDate randomJoinDate = LocalDate.of(2020parseInt(monthDigit), parseInt(dayDigit));
        return randomJoinDate;
    }
 
    // 주소
    public static List<String> gyeonggiLocal =
            Arrays.asList("연천군 ","포천시 ","동두천시 ","파주시 ","양주시 ","가평군 ","의정부시 ","고양시 ","김포시 ",
                    "남양주시 ","구리시 ","하남시 ","양평군 ","광주시 ","여주시 ","이천시 ","용인시 ","안성시 ","평택시 ",
                    "화성시 ","수원시 ","오산시 ","안산시 ","군포시 ","의왕시 ","안양시 ","과천시 ","부천시 ","광명시 ",
                    "성남시 ","시흥시 ");
 
    public static String generateRandomAddress() {
        Collections.shuffle(gyeonggiLocal);
        String randomAddress = "경기도 " + gyeonggiLocal.get(0);
        return randomAddress;
    }
}
 
 
cs

 

파이썬을 활용해서, 리액트 화면이 없는 상황에서 cmd로 즉시실행 처리를 해서 자바 컨트롤러를 실행합니다.

( thanks to. 호정 )

 

UserController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.mobeom.local_currency.user;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
 
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    UserService userService;
 
    @PostMapping(value = "/idCheck")
    public ResponseEntity<User> idCheck(@RequestBody User user) {
        Optional<User> idCheckResult = userService.findUserbyUserId(user.getUserId());
        if(idCheckResult.isPresent()) {
            return ResponseEntity.ok(idCheckResult.get());
        } else {
            return ResponseEntity.badRequest().build();
        }
    }
 
    @GetMapping(value = "/account-info/{userId}")
    public ResponseEntity<User> getOneInfo(@PathVariable String userId) {
        Optional<User> user = userService.findUserbyUserId(userId);
        if(user.isPresent()) {
            return ResponseEntity.ok(user.get());
        } else {
            return ResponseEntity.notFound().build();
        }
 
    }
 
    @PatchMapping(value = "/{id}")
    public ResponseEntity<User> updateUser(@PathVariable String id, @RequestBody User user) {
        Optional<User> findUser = userService.findUser(Long.valueOf(id));
        if(findUser.isPresent()) {
            User selectUser = findUser.get();
            Optional.ofNullable(user.getPassword()).ifPresent(password -> selectUser.setPassword(password));
            Optional.ofNullable(user.getDefaultAddr()).ifPresent(defaultAddress -> selectUser.setDefaultAddr(defaultAddress));
            Optional.ofNullable(user.getOptionalAddr()).ifPresent(optionalAddress -> selectUser.setOptionalAddr(optionalAddress));
            Optional.ofNullable(user.getEmail()).ifPresent(email -> selectUser.setEmail(email));
            return ResponseEntity.ok(userService.update(selectUser));
        } else {
            return ResponseEntity.notFound().build();
        }
    }
 
    @DeleteMapping(value = "/{id}")
    public ResponseEntity<User> deleteUser(@PathVariable String id) {
        Optional<User> findUser = userService.findUserbyUserId(id);
        if(findUser.isPresent()) {
            User selectUser = findUser.get();
            userService.delete(selectUser);
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
 
}
 
cs

 

User.java

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.mobeom.local_currency.user;
 
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.time.LocalDate;
 
@Entity
@Getter @Setter @ToString @NoArgsConstructor
@Table(name = "user", uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id"})})
public class User {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
 
    @Column(name = "user_id", nullable = false)
    private String userId;
 
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Column(name = "password", nullable = false)
    private String password;
 
    @Column(name = "name", nullable = false)
    private String name;
 
    @Column(name = "birth_date", nullable = false)
    private LocalDate birthDate;
 
    @Column(name = "gender", nullable = false)
    private String gender;
 
    @Column(name = "email", nullable = false)
    private String email;
 
    @Column(name = "join_date", nullable = false)
    private LocalDate joinDate;
 
    @Column(name = "withdraw_date")
    private LocalDate withdrawDate;
 
    @Column(name = "admin_key", nullable = false, columnDefinition = "boolean default 0")
    private Integer adminKey;
 
    @Column(name = "card_number")
    private String cardNumber;
 
    @Column(name = "default_addr", nullable = false)
    private String defaultAddr;
 
    @Column(name = "optional_addr")
    private String optionalAddr;
}
 
cs

UserRepository.java

1
2
3
4
5
6
7
8
9
package com.mobeom.local_currency.user;
 
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
 
@Repository
public interface UserRepository extends JpaRepository<User, Long>, CustomedUserRepository {
 
}
cs

 

UserRepositoryImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.mobeom.local_currency.user;
 
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;
import org.springframework.stereotype.Repository;
import java.util.Optional;
 
@Repository
interface CustomedUserRepository {
    Optional<User> findByUserId(String userId);
 
}
 
public class UserRepositoryImpl extends QuerydslRepositorySupport implements CustomedUserRepository  {
    @Autowired
    JPAQueryFactory queryFactory;
 
    UserRepositoryImpl() {
        super(User.class);
    }
 
    @Override
    public Optional<User> findByUserId(String userId) {
        QUser qUser = QUser.user;
        User findOne = queryFactory.selectFrom(qUser).where(qUser.userId.eq(userId)).fetchOne();
        return Optional.ofNullable(findOne);
    }
 
}
 
cs

 

UserServiceImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.mobeom.local_currency.user;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.Optional;
 
@Component
interface UserService {
 
    Optional<User> findUserbyUserId(String user);
    User update(User selectUser);
    void delete(User selectUser);
    Optional<User> findUser(Long id);
}
 
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserRepository userRepository;
 
    @Override
    public Optional<User> findUserbyUserId(String user) {
        Optional<User> idCheck = userRepository.findByUserId(user);
        return idCheck;
    }
 
    @Override
    public User update(User selectUser) {
        return userRepository.save(selectUser);
    }
 
    @Override
    public void delete(User selectUser) {
        userRepository.delete(selectUser);
    }
 
    @Override
    public Optional<User> findUser(Long id) {
        return userRepository.findById(id);
    }
 
}
 
cs

 

생성된 더미데이터의 user_id 하나를 선택합니다.

 

 

http://localhost:8080/users/account-info/bnRFZA97이런 형태로 브라우저에 호출합니다. 

아래와 같이 JSON 파일이 하나 호출되었습니다.

 

 

이제 프론트단 리액트와 axios 연결 과정으로 넘어갑니다.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함